Serde_json sample code doesn't match return?

I copied and pasted the sample code from serde_json github page.

and got this error.

let v: Value = serde_json::from_str(data)?;
| ^ cannot use the ? operator in a function that returns std::string::String

let data = r#"
        {
            "name": "John Doe",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;

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

Any idea what I might be doing wrong? Use is also added ==> "use serde_json::{Result, Value};"

The error is about using ? in a function that returns String, and not particular to serde_json.

You can

  • rewrite your function to return Option<String> and use .ok() before the ?
  • rewrite your function to return Result<String, _> and if necessary, use .map_err before the ?
  • keep returning String and use .unwrap() or .expect() instead of ?
3 Likes

Ah, yes, thank you for the extremely prompt response.

The error is gone after removing ?