json icon indicating copy to clipboard operation
json copied to clipboard

[Bug] Fails to parse root string array

Open tymur999 opened this issue 2 years ago • 3 comments

It can parse a root array of objects but not a root array of strings.

let val : Vec<String> = serde_json::from_str("['hello','two']").unwrap();

Expects a value after key 'hello' (but this is not a key, it is a string array)

tymur999 avatar Jun 08 '24 06:06 tymur999

ChatGPT recommends this alternative:

    let deserialized: Value = serde_json::from_str(json_str).unwrap();

    // Convert the serde_json::Value into a vector of strings
    if let Value::Array(array) = deserialized {
        let string_array: Vec<String> = array.into_iter()
            .filter_map(|v| v.as_str().map(|s| s.to_string()))
            .collect();

        // Print the vector of strings
        println!("{:?}", string_array);
    }
}

But as you can see, this is very unwieldy

tymur999 avatar Jun 08 '24 06:06 tymur999

['hello','two'] is not valid JSON.

dtolnay avatar Jun 08 '24 07:06 dtolnay

Originally this was stored in an env variable as ["hello","two"] which was for some reason parsed as [hello, two] which explains the err.

When I escape the " as \", it parses fine.

tymur999 avatar Jun 08 '24 18:06 tymur999