如何将Nolhmann JSON对象分成字符串

how to separate nolhmann json object's into strings

本文关键字:字符串 对象 JSON Nolhmann      更新时间:2023-10-16

>我正在尝试获取我的json obect,它存储来自.json文件的数据并将数据转换为字符串。我正在使用nolhmann json字典。

下面是 .json 文件:

"dictionary": [
   {"word": "MEAGRE", "definition": "A large European scinoid fish (Scina umbra or S. aquila),having white bloodless flesh. It is valued as a food fish. [Writtenalso maigre.]"},
    {"word": "GRUGRU WORM", "definition": "The larva or grub of a large South American beetle (Calandrapalmarum), which lives in the pith of palm trees and sugar cane. Itis eaten by the natives, and esteemed a delicacy."}

这是我的文件代码

    string filename = line.substr(input.size()+1, line.size());
    filename[11] = toupper(filename[11]);
    cout << filename << "n";

    ifstream i(filename);
    if (i.is_open()) {
        cout << "it is openn";
        json j;
        i >> j;
        for (json::iterator it = j.begin(); it != j.end(); ++it)
        {
            cout << *it << "n";
            //how to seperate into strings??
        }
    }

这是我第一次使用 json 文件,所以我仍在努力理解它们。那么有没有办法单独存储信息,这样我就可以有一个

字符串 = 单词中的信息

字符串 = 定义中的信息

因为所有不同的 JSON 字典都有不同的实现,所以我发现很难弄清楚这一点。

编辑 - 这是一个基于您的实际文件 JSON 的工作示例。注意 - 您发布的 JSON 无效,因此必须先修复它。我跳过了实际的文件读取部分,直接跳入其中,就好像文件已经被读入由静态 const 变量"json_data_from_file"表示的字符串中一样。如果您在将文件读取到 std::string 中时需要帮助,请告诉我。

#include <iostream>
#include <string>
#include "json.h"
static const std::string json_data_from_file = R"({
"dictionary": [{
               "word": "MEAGRE",
               "definition": "A large European scinoid fish (Scina umbra or S. aquila),having white bloodless flesh. It is valued as a food fish. [Writtenalso maigre.]"
               },
               {
               "word": "GRUGRU WORM",
               "definition": "The larva or grub of a large South American beetle (Calandrapalmarum), which lives in the pith of palm trees and sugar cane. Itis eaten by the natives, and esteemed a delicacy."
               }
               ]
})";
int main(int argc, const char * argv[]) {
    std::cout << "json data:n" << json_data_from_file << "n";
    try
    {
        // Now attempt to convert file data to json
        json jdict = json::parse(json_data_from_file);
        json j = json::parse(jdict["dictionary"].dump());
        for (const auto& i : j) {
            json jsonobj( i );
            std::string word = jsonobj["word"].dump();
            std::cout << "word: " << word << "n";
            std::string definition = jsonobj["definition"].dump();
            std::cout << "definition: " << definition << "n";
        }
    }
    catch (const std::exception& e) {
        //...
    }
    catch (...)
    {
        //...
    }
    return 0;
}