繁体   English   中英

解析JSON文件(C ++ Boost)

[英]Parse JSON file (C++ Boost)

我想使用Boost(属性树)库来解析以下有效的JSON文件:

{
    "user": {
        "userID": "5C118C8D-AA65-49C0-B907-348DE87D6665",
        "dateProperty": "05-06-2015"
    },
    "challenges": [
        {
            "question#1": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        },
        {
            "question": "answer",
            "value": 5
        }
    ] }

我确实验证了JSON格式是否正确。

我还咨询了几个网站,如:

但我仍然没有得到正确的结果。 我想收集“用户”和“挑战”作为键/值对。 最好的结果是将“挑战”(问题/答案)和用户信息(userID,dateProperty)写入可以写入std:map的std ::对。

任何建议,将不胜感激?

我想像往常一样,你对ptree如何存储JSON数组感到困惑?

这是一个快速演示:

住在Coliru

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <fstream>

int main()
{
    using namespace boost::property_tree;

    ptree pt;
    read_json(std::cin, pt);

    for (auto& challenge : pt.get_child("challenges"))
        for (auto& prop : challenge.second)
            std::cout << prop.first << ": " << prop.second.get_value<std::string>() << "\n";
}

打印:

question#1: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5
question: answer
value: 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM