vzdorr
September 27, 2022, 5:06am
#1
Does anybody know how I can process such json with serde_json?
{
"field1": "hello",
"array_field: ["1", "2", "3"],
"dup_field": 1,
"dup_field": 2
}
But message could be without dup too
{
"field1": "hello",
"array_field: ["1", "2", "3"],
"dup_field": 1,
}
My struct:
#[derive(Serialize, Deserialize, Debug)]
pub struct Message {
field1: Option<String>,
array_field:Vec<Value>,
dup_field: i64,
}
wezm
September 27, 2022, 5:23am
#2
How do you want dup_field
to be handled in the final result? Should it:
Keep all values, if so in what data structure? A Vec
?
Keep only the first value
Keep only the last value
vzdorr
September 27, 2022, 5:27am
#3
Keep only the first/last is ok
wezm
September 27, 2022, 6:59am
#4
Seems it's a bit tricky to achieve. There are some ideas here:
opened 11:51PM - 08 Apr 20 UTC
closed 11:53PM - 10 Apr 20 UTC
I came across the error: `Error("duplicate field `key`", line: x, column: y)`
…
Here is en example JSON file: ([yes this is valid json](https://stackoverflow.com/a/21833017/2037998))
```
{
"main_node": {
"key": "value",
"key": "value2"
}
}
```
Example Rust code:
```
#[derive(Serialize, Deserialize)]
struct MainNode{
key: String,
}
```
Looking for a solution I came across this: https://github.com/serde-rs/serde/issues/690
But this does not show a solution.
I also tried a enum, but this does not work (source: https://github.com/RReverser/serde-xml-rs/issues/55 )
Using an `Vec<String>` returns a `Error("invalid type: map, expected a sequence",...)`
I tried writing my own deserialize adapter but could not get it to work.
The JSON I'm using is from a Wireshark export, so this is used in other applications.
How should I handle this case? I could not find any solution to this.
Otherwise you could use an intermediate type to collect and de-dup extra fields then convert that. Like this:
H2CO3
September 27, 2022, 7:53am
#5
This has a much simpler solution using Value
:
let raw: Value = serde_json::from_str(EXAMPLE).expect("unable to parse JSON");
let msg: Message = serde_json::from_value(raw).expect("dup_field is missing");
Playground
1 Like
TIL that serde_json::Value
allows input to have duplicated keys, thanks!
1 Like
H2CO3
September 27, 2022, 9:04am
#7
To be honest, I just assumed that it does. Neither HashMap
nor BTreeMap
actively check for duplicate keys; they just blindly overwrite with the latest, so I figured that's also what a map-based Value::Object
would do, and the gamble paid off
2 Likes
vzdorr
September 27, 2022, 4:28pm
#8
I've used parsing fields to HashMap as below:
let parsed_message: HashMap<String, Value> = serde_json::from_str(message).unwrap();
As @H2CO3 mentioned it just uses the latest field.
That's not what was needed but it could be used like workaround
1 Like
system
Closed
December 26, 2022, 4:28pm
#9
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.