如何将Nolhmann JSON对象分成字符串
how to separate nolhmann json object's into strings
>我正在尝试获取我的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;
}
相关文章:
- 如何删除作为C++联合的成员变量的字符串对象
- 系统C 从字符串对象sc_uint
- 为什么<string>字符串对象需要 #include 而不是字符串文本?
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- C 字符串对象错误字符
- 创建兼容的字符串对象
- 从对象数组打印字符串对象
- 将指针分配给字符串对象的第一个也是最后一个索引
- 比较字符串对象等于向量中的元素
- 传递给 std::runtime_error 的 ctor 的字符串对象的生命周期是多少?
- 如何移动 std::ostringstream 的底层字符串对象?
- 将 const 引用传递给临时字符串对象在 C++ 中安全吗?
- getline 没有为字符串对象分配任何值
- 在c++中删除字符串对象
- 如何在没有收到需要分号编译错误的情况下从 c++ 中的函数返回字符串对象
- 你能在C++中返回字符串对象的局部变量吗?
- 将字符串对象的地址传递给函数
- C++:从字符串对象中提取整数
- 是否有理由使用字符串 => 索引到向量的映射,而不是字符串 => 对象?
- 控制对多线程程序中字符串对象的访问的最佳方法