21xrx.com
2024-09-20 00:22:09 Friday
登录
文章检索 我的文章 写文章
C++中使用nlohmann json解析数组
2023-06-30 15:01:40 深夜i     --     --
C++ nlohmann json 解析 数组

在C++中使用JSON作为数据格式变得越来越流行。当讨论C++中的JSON时,nlohmann json是最常用的库之一。它提供了一种直观的方法来创建,解析和操作JSON数据。在本文中,我们将重点讨论如何解析nlohmann json中的数组。

首先,让我们定义一个简单的json数组:


{

 "fruits": [

  

   "color": "orange"

  ,

  

   "color": "red"

  ,

  

   "name": "banana"

 ]

}

为了解析这个数组,我们需要使用以下代码:


#include <iostream>

#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {

 std::string json_string = R"({

   "fruits": [

    

     "name": "orange",

    

     "name": "apple",

    

     "name": "banana"

   ]

  })";

 json fruits_json = json::parse(json_string);

 for (json::iterator it = fruits_json["fruits"].begin(); it != fruits_json["fruits"].end(); ++it) {

  std::cout << "Name: " << (*it)["name"] << ", Color: " << (*it)["color"] << std::endl;

 }

 return 0;

}

以上代码首先将JSON字符串转换为json对象,然后循环遍历所有的水果并打印出它们的名称和颜色。

值得注意的是,对于数组,我们可以使用它的迭代器进行遍历。此外,要访问数组中的元素,我们只需要使用下标运算符[]来访问元素的属性。

总之,nlohmann json为我们提供了一种非常简单和方便的方法来解析JSON数据。你只需要按照上述代码进行操作并且使用迭代器来遍历数组即可。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复