serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.85k stars 555 forks source link

[Bug] Fails to parse root string array #1139

Closed tymur999 closed 3 months ago

tymur999 commented 3 months ago

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 commented 3 months ago

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

dtolnay commented 3 months ago

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

tymur999 commented 3 months ago

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.