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

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?



Solution 1:[1]

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

Solution 2:[2]

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);
}

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akida
Solution 2 E_net4 - Mr Downvoter
Solution 3