How to convert string to json in Rust

Created
Modified

Using Serde JSON

Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.

Adding dependencies

In Cargo.toml file we’ll add this information.

[dependencies]
#Using Serde's derive
serde = { version = "1.0", features = ["derive"] }

serde_json = "1.0"

Operating on untyped JSON values

Any valid JSON data can be manipulated in the following recursive enum representation. This data structure is serde_json::Value.

enum Value {
  Null,
  Bool(bool),
  Number(Number),
  String(String),
  Array(Vec),
  Object(Map),
}

For example,

use serde_json::Value;
use std::error::Error;

fn main() -> Result<(), Box> {
  let s = r#"
  {
    "name":"John",
    "age": 43,
    "ids": [3, 4, 5]
  }"#;

  // Parse the string of data into serde_json::Value.
  let v: Value = serde_json::from_str(s)?;

  println!("name:{} id0:{}", v["name"], v["ids"][0]);
  Ok(())
}
name:"John" id0:3

Parsing JSON as strongly typed data structures

Serde provides a powerful way of mapping JSON data into Rust data structures largely automatically.

use serde::{Deserialize, Serialize};
use std::error::Error;

#[derive(Serialize, Deserialize)]
struct Person {
  name: String,
  age: u8,
  ids: Vec,
}

fn main() -> Result<(), Box> {
  let s = r#"
  {
    "name":"John",
    "age": 43,
    "ids": [3, 4, 5]
  }"#;

  // Parse the string of data into a Person object.
  let v: Person = serde_json::from_str(s)?;

  println!("name:{} id0:{}", v.name, v.ids[0]);
  Ok(())
}
name:"John" id0:3

Using json! macro

Serde JSON provides a json! macro to build serde_json::Value objects with very natural JSON syntax.

use serde_json::json;
use std::error::Error;

fn main() -> Result<(), Box> {
  let v = json!(
  {
    "name":"John",
    "age": 43,
    "ids": [3, 4, 5]
  });

  println!("name:{} id0:{}", v["name"], v["ids"][0]);
  Ok(())
}
name:"John" id0:3

Serializing data structures

A data structure can be converted to a JSON string by serde_json::to_string.

use serde::{Deserialize, Serialize};
use std::error::Error;

#[derive(Serialize, Deserialize)]
struct Person {
  name: String,
  age: u8,
  ids: Vec,
}

fn main() -> Result<(), Box> {
  let v = Person {
    name: "Jhon".to_string(),
    age: 10,
    ids: vec![3, 4, 5],
  };

  let s = serde_json::to_string(&v)?;

  println!("{}", s);
  Ok(())
}
{"name":"Jhon","age":10,"ids":[3,4,5]}

Related Tags