Home > Enterprise >  How do I get the string value of a JSON value without quotes ("")?
How do I get the string value of a JSON value without quotes ("")?

Time:05-23

I have this code:

let data = r#"
{
"name": "john",
"address": "street 34",
"age": 22,
"phones": [
" 34 21213232367",
" 34 82837826476"
]
}
"#;

let value1: Value = serde_json::from_str::<Value>(data)?;
println!("name {} ", value1["name"]);

This prints =>

name "john"

However, I'd like to print

name john

Without "", how can I do it?

CodePudding user response:

Use the JsonValue::as_str method (if you are sure that the value is a str):

println!("name {} ", value1["name"].as_str().expect("Value is a str"));

Playground

CodePudding user response:

Serde JSON is not mean to be used with Value. Prefer declaring a struct that represents your JSON object, like this:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Contact {
    name: String,
    address: String,
    age: u8,
    phones: Vec<String>,
}

// or non Owned version but prefer owned version
// unless you know what you are doing
// #[derive(Debug, Deserialize)]
// struct Contact<'a> {
//     name: &'a str,
//     address: &'a str,
//     age: u8,
//     phones: Vec<&'a str>,
// }

fn main() {
    let data = r#"
{
    "name": "john",
    "address": "street 34",
    "age": 22,
    "phones": [
        " 34 21213232367",
        " 34 82837826476"
    ]
}
"#;

    let john: Contact = serde_json::from_str(data).unwrap();
    println!("name {} ", john.name);
}

CodePudding user response:

if let Some(Value::String(string)) = value1["name"] {
  println!("{}", string);
}
  • Related