Is it possible to get value useing json_serde::from_str() of a json where string is does not have " around it?

Viewed 113

I am not able to extract value from a JSON where strings don't have double quotes around then in json_serde. Json_serde::Value is failing in json_serde::from_str()

use serde_json::{Result, Value};
fn main() -> Result<()>{
      let raw_text = r##"{
          "url" : https://www.google.com
      }"##;

      println!("{}",raw_text);

      let v: Value = serde_json::from_str(raw_text)?;
      //let detail: Value  =  serde_json:: from_str(&v["detail"].to_string())?;
      println!("{}", v["url"]);
      Ok(())
}

Output

json git:master ❯❯❯ cargo run                                                                                                                                                                                                                ✭
   Compiling json v0.1.0 (/home/d/Documents/RustScripts/json)
    Finished dev [unoptimized + debuginfo] target(s) in 0.21s
     Running `target/debug/json`
{
          "url" : https://www.google.com
      }
Error: Error("expected value", line: 2, column: 19)

1 Answers

The data is not in JSON format, so it is not possible for serde_json to deserialize it. Since YAML is a superset of JSON and accepts strings without double-quotes, you can use serde_yaml for this specific case:

use serde_json::Value;
use serde_yaml::Result;

fn main() -> Result<()>{
    let raw_text = r##"{
        "url" : https://www.google.com
    }"##;
    let v: Value = serde_yaml::from_str(raw_text)?;
    println!("{}", v["url"]);
    Ok(())
}

This may cause problems if it's possible for the string to be interpreted as a different type (e.g. yes as a boolean). But if the unquoted strings are all URLs, it should work.

A better solution would be to fix the system that generates this almost-JSON data.

Related