JSON数据解析

        在C++中解析JSON文件通常需要使用外部库,因为C++标准库本身不直接支持JSON。可以使用的C++ JSON库包括nlohmann/json、RapidJSON、JsonCpp等,此处我们使用nlohmann/jscon库解析JSON字符串。

安装

使用包管理器

sudo apt-get update  
sudo apt-get install nlohmann-json3-dev


从源代码编译安装

// 克隆
git clone https://github.com/nlohmann/json.git  
cd json

// 编译安装
mkdir build  
cd build  
cmake ..  
sudo make install

演示代码

#include <iostream>  
#include <nlohmann/json.hpp>  
  
using json = nlohmann::json;  
using namespace std;  
  
int main() {  
    // 你的JSON字符串  
    string jsonStr = R"({  
        "Card Configuration": {  
            "Function": [  
                {  
                    "Card": "10",  
                    "HW": "AVI32",  
                    "Pogoblock": "G3,G1",  
                    "Type": "HD"  
                },  
                {  
                    "Card": "11",  
                    "HW": "AVI32",  
                    "Pogoblock": "A1,A2",  
                    "Type": "HD"  
                },  
                {  
                    "Card": "12",  
                    "HW": "AVI32",  
                    "Pogoblock": "G5,F5",  
                    "Type": "HD"  
                }  
            ]  
        }  
    })";  
  
    // 解析JSON字符串  
    json jsonObj = json::parse(jsonStr);  
  
    // 访问"Card Configuration"下的"Function"数组  
    if (jsonObj.contains("Card Configuration") && jsonObj["Card Configuration"].contains("Function") && jsonObj["Card Configuration"]["Function"].is_array()) {  
        for (const auto& func : jsonObj["Card Configuration"]["Function"]) {  
            // 访问每个Function对象的属性  
            cout << "Card: " << func["Card"] << ", HW: " << func["HW"]  
                 << ", Pogoblock: " << func["Pogoblock"] << ", Type: " << func["Type"] << endl;  
        }  
    } else {  
        cout << "JSON structure does not match the expected format." << endl;  
    }  
  
    return 0;  
}

运行结果

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值