C++ Json文件读写示例

这段代码展示了如何使用json11库处理和写入JSON数据。它遍历帧数据,为每个帧创建一个包含对象框信息的数组,并将结果保存到'result.json'文件中。之后,代码读取该文件并解析JSON数据,提取每个框的坐标、ID和得分信息。
摘要由CSDN通过智能技术生成

#include "json11.hpp"

// write json data

json11::Json::array json_results;

for(int i = 0; i < frames; i++) {
    // process
    // ....
    json11::Json::array frame_result;
    json11::Json::object frame_info;
    frame_info["frame"] = frame;
    frame_result.push_back(frame_info);
    for (auto obs : obsOutput) {
        json11::Json::object tmp_obj;
        json11::Json::array rect;
        rect.push_back(obs.firstPointX);
        rect.push_back(obs.firstPointY);
        rect.push_back(std::abs(obs.thirdPointX - obs.firstPointX));
        rect.push_back(std::abs(obs.thirdPointY - obs.firstPointY));
        tmp_obj["rect"] = rect;
        tmp_obj["id"] = obs.trackId;
        tmp_obj["score"] = obs.score; //float type
        frame_result.push_back(tmp_obj);
    }
    json_results.push_back(frame_result);
}

std::string json_str;
json11::Json rootJson(json_results);
rootJson.dump(json_str);
std::string json_file =  "result.json";
std::ofstream file(json_file, std::ofstream::out);
file << json_str;
file.close();

// read json data

std::string json_file =  "result.json";
std::ifstream file(json_file, std::ofstream::in);
std::string line_str, err;
std::getline(file, line_str);
json11::Json json_results = json11::Json::parse(line_str, err);
file.close();

for(int i = 0; i < frames; i++) {
    // process
    // ...
    json11::Json::array json_array = json_results.array_items();
    auto items = json_array[frame].array_items();
    int frame_num = items[0]["frame"].int_value();
    for (auto it = items.begin() + 1; it != items.end(); it++) {
    cv::Rect rect;
    rect.x = (*it)["rect"][0].int_value();
    rect.y = (*it)["rect"][1].int_value();
    rect.width = (*it)["rect"][2].int_value();
    rect.height = (*it)["rect"][3].int_value();
    int id = (*it)["id"].int_value();
    float score = (float)(*it)["score"].number_value();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值