【问题标题】:C++ nlohmann json multiple json from fileC ++ nlohmann json来自文件的多个json
【发布时间】:2017-03-04 02:59:17
【问题描述】:

我一直在搞乱 nlohmann 的 json 库,但我不知道我错过了什么。我正在尝试一次读取一堆 json 对象,并且该文件每行有 1 个 json 对象,我正在尝试解析所有这些对象并将其存储到一个向量中。

int main(){
vector <json> alljSon;
std::ifstream i("test.json");
while (i.good()) {
    json j;
    i >> j;
    alljSon.push_back(j);
}

return 0;

}

问题是如果有超过 1 个 json 对象,它会给我一个错误消息。 “解析错误 - 意外'{';预期输入结束”std::basic_string,std::allocator >。有什么修复吗?

【问题讨论】:

  • 您可以发布您的代码,因为它包含超过 1 个 json 对象吗?
  • 什么意思?这是我目前拥有的所有代码。您是在询问 test.json 文件吗?
  • nlomann json 库不支持从流中读取连接的 json。见:github.com/nlohmann/json/issues/210.

标签: json file c++11 stream


【解决方案1】:

一个不错的方法是将整个文件解析为 JSON,然后遍历该 JSON 并将值添加到向量中。

#include <nlohmann/json.hpp>
#include <vector>
#include <fstream>

using nlohmann::json;

int main()
{
    std::vector <json> alljSon;
    std::ifstream i("test.json");
    json j = json::parse(i);
    for (auto it = j.begin(); it != j.end(); ++it)
    {
        if (j.is_array())
        {
            alljSon.push_back(it.value());
        }
        else
        {
            // If it's not an array, it's an object, and from what I understood you want the key too.
            alljSon.push_back({it.key(), it.value()});
        }
    }
    return 0;
}

How to iterate over JSON objects.

【讨论】:

    猜你喜欢
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多