如何使用jsoncpp将列表中的特定值保存到txt?

ka

我有yahoo finance json文件,要从quote列表中隔离Date,Close和volume,并用逗号分隔的相同顺序将其保存在单个文本文件中。这是我的json脚本。

Json::Value root;   // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse( YahooJson, root );
if(not parsingSuccessful)
 {
   // Report failures and their locations
   // in the document.
   std::cout<<"Failed to parse JSON"<<std::endl
       <<reader.getFormatedErrorMessages()
       <<std::endl;
   return 1;
 }else{
 std::cout<<"\nSucess parsing json\n"<<std::endl;
 std::cout << root<< std::endl;
 std::cout <<"No of Days = "<< root["query"]["count"].asInt() << std::endl;

//below for loop returns an error
 for (auto itr : root["query"]["result"]["quote"]) {
    std::string val = itr.asString();

} 


 }

我能够成功获取json值并打印,root["query"]["count"].asInt()但是当我转到列表values(quote)时,我不知道如何遍历引用(query-> result-> quote)以获取Date,close和volume值?

编辑

也尝试过这种方法

const Json::Value& quotes = root["query"]["results"]["quote"];
for (int i = 0; i < quotes.size(); i++){
    std::cout << "    Date: " << quotes[i]["Date"].asString();
    std::cout << "   Close: " << quotes[i]["Close"].asFloat();
    std::cout << "  Volume: " << quotes[i]["Volume"].asFloat();
    std::cout << std::endl;
}

它仅在输出为Date时有效。对于关闭和体积输出,它会退出并显示运行时错误消息以及此错误

what() type is not convertible to string
埃文·范德泽(Evan VanderZee)

您尚未指定要使用的JSON库,并且我对Yahoo财务数据的了解还不够,无法知道确切的字段名称,但是如果您使用的是JsonCpp库,该库在此处提供了文档,并且您正在询问如何在JSON数组上进行迭代,那么使用迭代器进行迭代的一种方法如下所示

const Json::Value quote = root["query"]["results"]["quote"];
for (Json::ValueConstIterator itr = quote.begin(); itr != quote.end(); ++itr)
{
  const Json::Value date = (*itr)["Date"];
  const Json::Value close = (*itr)["Close"];
  const Json::Value volume = (*itr)["Volume"];
  std::cout << "Date: " << date.asString() << std::endl;
  std::cout << "Close: " << close.asString() << std::endl;
  std::cout << "Volume: " << volume.asString() << std::endl;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将列表保存到.txt文件

如何使用python将视频的特定帧保存到文件夹中?

如何将字典列表保存到文件中?

将JList保存到Txt文件中

如何从csv读取不带标题的列,并使用Python将输出保存到txt文件中?

如何将列表保存到Spark中?

如何使用Spark将Scala列表持久保存到mongodb

如何将下拉列表值保存到Django中的数据库

如何将Vim命令保存到特定缓冲区中并再次使用

如何将保存在.txt文件中的过程值保存到C中的4个不同数组中

将List <>保存到.txt文件中

如何将列表中的结果保存到.txt文件?

如何将种子随机sort_by {rand}的随机值保存到红宝石列表中?

如何将JTextArea中的值保存到JTable中?

如何使用python将列表中包含字典的json保存到csv中

如何使用 Mybatis 将 JavaBean 包含列表保存到 Sql?

如何将值保存到 C# 中的列表

如何将单词保存到动态列表中

如何将值从 ansible 中的多个任务保存到列表 var 中?

如何将列表保存到 .txt?

单击下载按钮时,如何将 MySQL 数据库中的值保存到 .txt 文件中?

如何使用 OpenCV 将数组(帧)列表保存到视频中?

如何使用 php 将 echo 的所有变量结果保存到 txt 文件中?

如何将包含列表的字典保存到文件中?

如何在python中使用opencv将视频的特定部分保存到单独的视频中?

如何使用列表推导式将整数和小数保存到每个列表中?

使用 DateTime 作为标题将列表保存到 json 中

如何使用cropImage()将裁剪后的图像保存到Flutter中的特定文件夹

Python:如何将列表中的文本+元素保存到txt文件