Json存储树形结构

Json写入树形结构,并转成string,可被其他模块(比如,cgi)调用:

 

#include <json/json.h>  
...

struct Node{
    string tag_name;
    vector<string> children_tag_key;
};

unordered_map<string, Node> tag_node_dict;

...

Json::Value tag_tree_json_build(string tag_key) 
{
    Json::Value jv_node;
    string tag_name = tag_node_dict[tag_key].tag_name;
    jv_node["name"] = tag_name;

    for (uint32_t i=0; i<(tag_node_dict[tag_key].children_tag_key).size(); i++) 
    {
        string tag_key_son = tag_node_dict[tag_key].children_tag_key[i];
        Json::Value jv_son = tag_tree_json_build(tag_key_son);
        jv_node["children"].append(Json::Value(jv_son));
    }
    return jv_node;
}

...

Json::Value jv_root = tag_tree_json_build("root"); 
Json::FastWriter writer; 
string tag_tree =  writer.write(jv_root);

 

下面是手动构造,以便更好理解上面的递归


// a demo manually
Json::Value jv_root;
jv_root["name"] = Json::Value("root");
Json::Value node_1, node_2, node_3, node_4, node_1_1, node_1_2;

node_1["name"] = Json::Value("动物");
node_1_1["name"] = Json::Value("猫");
node_1_2["name"] = Json::Value("狗");
node_1["children"].append(Json::Value(node_1_1));
node_1["children"].append(Json::Value(node_1_2));

node_2["name"] = Json::Value("植物");
node_3["name"] = Json::Value("生活用品");
node_4["name"] = Json::Value("交通工具");

jv_root["children"].append(Json::Value(node_1));  
jv_root["children"].append(Json::Value(node_2));  
jv_root["children"].append(Json::Value(node_3));  
jv_root["children"].append(Json::Value(node_4));  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值