1

So I have a problem. I have a base serde_json Value that goes like this:

{
  "person": [
         {
          "country": "Jamaica",
          "name: "John",
         },
         ...
    ],
  ...
}

I can easily insert one object as:

{
  "person":
         {
          "country": "Jamaica",
          "name: "John",
         }
}

But I have no idea how to add them dynamically into an array like in the first example. I used to do it with push with the json crate, but this doesn't seem to exist with serde_json. Any ideas?

Kramen
  • 33
  • 4
  • 1
    You declare `let mut vec = Vec`, build it using `vec.push(...)`, and insert it into the JSON map as `Value::Array(vec)`. – user4815162342 Mar 20 '21 at 22:57
  • I might not have explained the problem very well. That solution seems very appropriate but there's an additional hurdle. I'm essentially iterating through some data, and I wanted to only go through it once. However, the first keys, like "person" in the example, aren't in order and I have to add the correct object to the array of the correct first key. So I can't really build an entire Vec first, because I'd have to iterate through the whole data to make sure I had all of them that belonged to the key "person" – Kramen Mar 20 '21 at 23:00
  • 1
    If you can't keep the Vec around, just [get it each time](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=470d57b0c3405516678b502e604283fa)? – kmdreko Mar 21 '21 at 03:41
  • That's perfect, I can't believe I didn't realize it. – Kramen Mar 21 '21 at 09:31

1 Answers1

0

Inserting a Value::Array into a Value::Object

let mut v: Vec<Value> = Vec::new();

// ... fill in the vec with some Value::Object's as you like it ...
// ... in your case with some "Persons"

let a = Value::Array(v);
let mut map: serde_json::Map<String,Value> = serde_json::Map::new();
map.insert("person",a);
let o = Value::Object(map);

The Rust-Doc contains more possibilities and information: a link

Dragis
  • 33
  • 5