Rust

Parse json to data structures in Rust

Parse json to object or list of objects is done a little bit differently when compared to other languages like Go or Java.

Photo by W on Unsplash

For example we want to get json() return type from the Http API, we have to define the data structures of the json response accordingly. Let’s say the response from API is a list of object which contains the following fields:

auth_resource_path: String,
field: String,
id: String,
project_id: String,
type: String,
value: String,

Then we must define the struct type for this object.

Notice that in the field of object we have “type” which is one of the restricted keyword in Rust.

In this case, we can use serd to rename the field to type

#[serde(rename = "type")]

The json value consist a list of objects, so we use the type Vector of object.

let json_value: Vec<SearchElement>  = res.json().await?;

The complete main function for parse json value look like this:

Hope it helps.

~~~PEACE~~~

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store