0

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?

Pawan Bisht
  • 215
  • 2
  • 9

1 Answers1

1

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();
Rick Rainey
  • 11,096
  • 4
  • 30
  • 48