Home > Mobile >  Getting "trailing characters" error when trying to parse string with serde_json
Getting "trailing characters" error when trying to parse string with serde_json

Time:03-31

I need to convert a specific string in serde_json::Value, but getting a trailing character error while using:

let new_str = "73723235c81ebbec0"
let json_value: serde_json::Value = serde_json::from_str(new_str).unwrap();

Error:

trailing characters at line 1 column 9

Is there any way to convert these kinds of strings to serde_json::Value?

CodePudding user response:

Looking at the repo for serde_json, it appears from their test cases this is expected behavior. For example, see this test case. Since your string starts with numeric values, it is attempting to parse as a number and then fails when it reaches the 'c' in position 9.

Rather than calling from_str(), use to_value(). This will give you a String variant of the Value enum.

let json_value: serde_json::Value = serde_json::to_value(&new_str).unwrap();

Also, if you use to_value(), you can omit the type identifier for your variable, which I believe is probably more idiomatic.

let json_value = serde_json::to_value(&new_str).unwrap();
  • Related