How to build json arrays or objects dynamically with serde_json?

我的梦境 提交于 2021-01-29 12:30:51

问题


I need to build a json object at runtime. For now, just a simple {"key": "stringvalue"} object. But each key/val pair must be added in a loop.

This seems really simple/basic, but I didn't find any good examples or docs on it. I did finally manage to make something work, but it seems too convoluted to be the right way.

Can anyone post a working example?


回答1:


You can do this with serde_json::Value:

use serde_json::{Map, Value};

let mut map = Map::new();

// assuming keys_vals is a Vec<(String, String)>
for (key, val) in keys_vals.into_iter() {
    map.insert(key, Value::String(val));
}

let obj = Value::Object(map);

If you need to have the object constructed and still update the map:

let mut obj = Value::Object(map);

if let Value::Object(ref mut map) = obj {
    map.insert(key, val);
}


来源:https://stackoverflow.com/questions/59047280/how-to-build-json-arrays-or-objects-dynamically-with-serde-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!