DEV Community


Posted on

Parsing Json in Rust easily from API call

JSON has become one of the most popular data interchange formats on the web, thus it's vital that server-side languages handle it well.
Actually OpenAPI specification also use JSON format.
Fortunately, working with JSON is an area where Rust excels, owing in large part to the serde and serde json crates.
When compared to other languages such as Python or Java, parsing JSON to object or list of objects is done slightly differently.

In this article I will explain how to work with JSON. I will use the previous API I wrote, check my previous article before continue.

How to use serde_json?

First of all, your dependencies should looks like this:

rocket = "0.4.11"
rocket_codegen = "0.4.11"
http = "0.2"
reqwest = { version = "0.11", features = ["blocking","json"] }

serde = { version = "1", features = ["derive"] }
serde_json = "1"

Enter fullscreen mode Exit fullscreen mode

To begin, you must add the Serialize and Deserialize traits on your type. To use derive macros check if the derive: feature is enabled in your dependencies.
Here I use a method called ORM (Object–relational mapping) that consists to converts data between type systems.
My Coin structure looks like this with derive marco. On each type you have to declare this traits on your type.

#[derive(Debug, Deserialize, Serialize)]
struct Coin {
    id: String,
    symbol: String,
    market_data: MarketData

Enter fullscreen mode Exit fullscreen mode

I define the other struct depending on what I need based on the given JSON.

use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
struct CurrentPrice {
    usd: i64
#[derivedestruct(Debug, Deserialize, Serialize)]

struct MarketData {
    pub current_price: CurrentPrice
Enter fullscreen mode Exit fullscreen mode

Let's dive into the code

After sending the request to backend-api , if the status code is success, then I try to deserialize the response body using serde then saved my JSON response in the "json_value" variable.

    let json_value = resp.json::<Coin>();
        match json_value {
                Ok(format!(" Coin:{} Symbol:{} price:{:?}" ,, value.symbol,  value.market_data.current_price.usd))  
        Err(value) => { Ok(format!("value{:?}",value))}

        let response = resp.text().unwrap();
        Ok(format!("{} is not a coin!", response))
Enter fullscreen mode Exit fullscreen mode

The "json_value" variable is "Result" type so I need to unwrap it in order to get the Coin Object.
I used match then I print the desired data on the HTML page with the help of format.

This is the final result:
Image description

I finished a series of small and simple articles about API in a Rust context. I will wrote a more advanced article in the near future.

Between this you can check our API Solution at

If you are interested in more topic related to Rust join our Discord Server:

Top comments (0)