《C++避坑神器·二十五》简单搞懂json文件的读写之遍历json文件读写

发布时间:2023年12月25日

json.hpp库放在文章末尾

1、遍历json文件读写

(1)插入新键值对到json之情形1
原来json文件如下所示:

{
  "Connection": {
    "IpAddress": "192.168.20.1",
    "Rock": 0,
    "Solt": 1
  }, 
  "DataBaseNumber":7,
  "hardWare":{
	"Axis1_offset_Enable": "0.0",
	"Axis1_offset_Stop": "0.1",
	"Axis1_offset_Speed": "2.0",
	"Axis1_offset_Mov": "4.0",
	"Axis1_offset_Pos": "6.0",
	"Axis1_offset_Busy": "8.1",
	"Axis2_offset_Enable": "10.0",
	"Axis2_offset_Stop": "10.1",
	"Axis2_offset_Speed": "12.0",
	"Axis2_offset_Mov": "14.0",
	"Axis2_offset_Pos": "16.0",
	"Axis2_offset_Busy": "18.1"
  }
}

现想要在末尾插入新的键值对如下:

{
  "Connection": {
    "IpAddress": "192.168.20.1",
    "Rock": 0,
    "Solt": 1
  }, 
  "DataBaseNumber":7,
  "hardWare":{
	"Axis1_offset_Enable": "0.0",
	"Axis1_offset_Stop": "0.1",
	"Axis1_offset_Speed": "2.0",
	"Axis1_offset_Mov": "4.0",
	"Axis1_offset_Pos": "6.0",
	"Axis1_offset_Busy": "8.1",
	"Axis2_offset_Enable": "10.0",
	"Axis2_offset_Stop": "10.1",
	"Axis2_offset_Speed": "12.0",
	"Axis2_offset_Mov": "14.0",
	"Axis2_offset_Pos": "16.0",
	"Axis2_offset_Busy": "18.1"
  },
   "time":{
	  "maxtime":100,
	  "mintime":0
  }
}

代码实现:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::ifstream file("test.json");
    if (!file.is_open()) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    json jsonData;
    file >> jsonData;
    file.close();

    // 创建新的键值对
    json timeData = {
        {"maxtime", 100},
        {"mintime", 0}
    };

    // 将新的键值对插入到现有的 JSON 数据中
    jsonData["time"] = timeData;

    // 将更新后的 JSON 数据写入文件
    std::ofstream outputFile("test.json");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outputFile << std::setw(4) << jsonData << std::endl; // 美化输出,每个元素缩进四个空格
    outputFile.close();

    return 0;
}

(2)插入新键值对到json之情形2
原来的json文件如下:

{
  "Connection": {
    "IpAddress": "192.168.20.1",
    "Rock": 0,
    "Solt": 1
  }, 
  "DataBaseNumber":7,
  "hardWare":{
	"Axis1_offset_Enable": "0.0",
	"Axis1_offset_Stop": "0.1",
	"Axis1_offset_Speed": "2.0",
	"Axis1_offset_Mov": "4.0",
	"Axis1_offset_Pos": "6.0",
	"Axis1_offset_Busy": "8.1",
	"Axis2_offset_Enable": "10.0",
	"Axis2_offset_Stop": "10.1",
	"Axis2_offset_Speed": "12.0",
	"Axis2_offset_Mov": "14.0",
	"Axis2_offset_Pos": "16.0",
	"Axis2_offset_Busy": "18.1"
  }
}

现想要在末尾插入一个数组,如下所示:

{
  "Connection": {
    "IpAddress": "192.168.20.1",
    "Rock": 0,
    "Solt": 1
  }, 
  "DataBaseNumber":7,
  "hardWare":{
	"Axis1_offset_Enable": "0.0",
	"Axis1_offset_Stop": "0.1",
	"Axis1_offset_Speed": "2.0",
	"Axis1_offset_Mov": "4.0",
	"Axis1_offset_Pos": "6.0",
	"Axis1_offset_Busy": "8.1",
	"Axis2_offset_Enable": "10.0",
	"Axis2_offset_Stop": "10.1",
	"Axis2_offset_Speed": "12.0",
	"Axis2_offset_Mov": "14.0",
	"Axis2_offset_Pos": "16.0",
	"Axis2_offset_Busy": "18.1"
  },
   "ROIS":[
    {
	"Name":"ROI1",
	"weight":1
    },
    {
	"Name":"ROI2",
	"weight":0.5
    }
  ]
}

代码实现:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::ifstream file("your_file.json");
    if (!file.is_open()) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    json jsonData;
    file >> jsonData;
    file.close();

    // 创建新的 ROIS 数据
    json roisData = {
        {"Name", "ROI1"},
        {"weight", 1}
    };

    json roisData2 = {
        {"Name", "ROI2"},
        {"weight", 0.5}
    };

    // 将新的 ROIS 数据插入到 JSON 数据末尾
    jsonData["ROIS"].push_back(roisData);
    jsonData["ROIS"].push_back(roisData2);

    // 将更新后的 JSON 数据写入文件
    std::ofstream outputFile("updated_file.json");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outputFile << std::setw(4) << jsonData << std::endl; // 美化输出,每个元素缩进四个空格
    outputFile.close();

    return 0;
}

(3)插入新键值对到json之情形3
原先的json文件如下:

{
  "test": [
    {
      "FixedParameters": {
		"bit_depth": 255,
        "dynamic_range": 0.8
      },
	  "IsUseROIs":{
		"isUseROIs":false,
		"ROIS":[
		  {
			"Name":"ROI1",
			"weight":1
		  }
		]
	  },
      "Index": 1
    },
    {
      "FixedParameters": {
		"bit_depth": 255,
        "dynamic_range": 0.8
      },
	  "IsUseROIs":{
		"isUseROIs":false,
		"ROIS":[
		  {
			"Name":"ROI1",
			"weight":1
		  }
		]
	  },
      "Index": 2
    }
  ]
}

现想要在数组的两个内容里面index和weight下面插入新的键值对,如下所示:

{
  "test": [
    {
      "FixedParameters": {
       "bit_depth": 255,
        "dynamic_range": 0.8
      },
      "IsUseROIs":{
	"isUseROIs":false,
	"ROIS":[
	    {
		"Name":"ROI1",
		"weight":1,
		"width": 100
	    }
	 ]
      },
      "Index": 1,
      "name": "vimba"
    },
    {
      "FixedParameters": {
      "bit_depth": 255,
      "dynamic_range": 0.8
      },
      "IsUseROIs":{
	"isUseROIs":false,
	"ROIS":[
	    {
		"Name":"ROI1",
		"weight":1,
		"width": 100
	    }
	 ]
       },
       "Index": 2,
       "name": "vimba"
     }
  ]
}

代码实现:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::ifstream file("your_file.json");
    if (!file.is_open()) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    json jsonData;
    file >> jsonData;
    file.close();

    // 遍历 AutoExposure 数组
    if (jsonData.find("test") != jsonData.end() && jsonData["test"].is_array()) {
        for (auto& entry : jsonData["test"]) {
            // 获取 ROIS 数组
            if (entry.find("IsUseROIs") != entry.end() && entry["IsUseROIs"].find("ROIS") != entry["IsUseROIs"].end()) {
                // 在每个 ROIS 数组元素后插入新键值对 "width": 100
                for (auto& rois_entry : entry["IsUseROIs"]["ROIS"]) {
                    rois_entry["width"] = 100;
                }
            }

            // 在每个对象中添加新键值对 "name": "vimba"
            entry["name"] = "vimba";
        }
    }

    // 将更新后的 JSON 数据写入文件
    std::ofstream outputFile("updated_file.json");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outputFile << std::setw(4) << jsonData << std::endl; // 美化输出,每个元素缩进四个空格
    outputFile.close();

    return 0;
}

(4)修改原先的键值对之情形1
原先的json文件如下:

{
  "test": [
    {
      "FixedParameters": {
		"bit_depth": 255,
        "dynamic_range": 0.8
      },
	  "IsUseROIs":{
		"isUseROIs":false,
		"ROIS":[
		  {
			"Name":"ROI1",
			"weight":1
		  }
		]
	  },
      "Index": 1
    },
    {
      "FixedParameters": {
		"bit_depth": 255,
        "dynamic_range": 0.8
      },
	  "IsUseROIs":{
		"isUseROIs":false,
		"ROIS":[
		  {
			"Name":"ROI1",
			"weight":1
		  }
		]
	  },
      "Index": 2
    }
  ]
}

现想修改每个数组元素里面index和weight值,代码如下:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::ifstream file("your_file.json");
    if (!file.is_open()) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    json jsonData;
    file >> jsonData;
    file.close();

    // 遍历 AutoExposure 数组
    if (jsonData.find("test") != jsonData.end() && jsonData["test"].is_array()) {
        for (auto& entry : jsonData["test"]) {
            // 修改每个对象的 "Index" 值为 10 和 20
            entry["Index"] = (entry["Index"] == 1) ? 10 : 20;  //这里可以通过json其他键值对判断目前遍历的是数组第几个元素

            // 修改每个对象的 "weight" 值为 0.5 和 0.7
            if (entry.find("IsUseROIs") != entry.end() && entry["IsUseROIs"].find("ROIS") != entry["IsUseROIs"].end()) {
                for (auto& rois_entry : entry["IsUseROIs"]["ROIS"]) {
                    rois_entry["weight"] = (rois_entry["weight"] == 1) ? 0.5 : 0.7;  //这里可以通过json其他键值对判断目前遍历的是数组第几个元素
                }  
            }
        }
    }

    // 将更新后的 JSON 数据写入文件
    std::ofstream outputFile("updated_file.json");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outputFile << std::setw(4) << jsonData << std::endl; // 美化输出,每个元素缩进四个空格
    outputFile.close();

    return 0;
}

(5)修改原先的键值对之情形2
原先的json文件如下:

{
  "Connection": {
    "IpAddress": "192.168.20.1",
    "Rock": 0,
    "Solt": 1
  }, 
  "DataBaseNumber":7,
  "hardWare":{
	"Axis1_offset_Enable": "0.0",
	"Axis1_offset_Stop": "0.1",
	"Axis1_offset_Speed": "2.0",
	"Axis1_offset_Mov": "4.0",
	"Axis1_offset_Pos": "6.0",
	"Axis1_offset_Busy": "8.1",
	"Axis2_offset_Enable": "10.0",
	"Axis2_offset_Stop": "10.1",
	"Axis2_offset_Speed": "12.0",
	"Axis2_offset_Mov": "14.0",
	"Axis2_offset_Pos": "16.0",
	"Axis2_offset_Busy": "18.1"
  }
}

现想修改修改Axis2_offset_Busy为18.2,代码如下:

#include <iostream>
#include <fstream>
#include "json.hpp"

using json = nlohmann::json;

int main() {
    std::ifstream file("your_file.json");
    if (!file.is_open()) {
        std::cerr << "Failed to open file." << std::endl;
        return 1;
    }

    json jsonData;
    file >> jsonData;
    file.close();

    // 修改特定键的值
    if (jsonData.find("hardWare") != jsonData.end()) {
        jsonData["hardWare"]["Axis2_offset_Busy"] = "18.2";
    }

    // 将更新后的 JSON 数据写入文件
    std::ofstream outputFile("updated_file.json");
    if (!outputFile.is_open()) {
        std::cerr << "Failed to open file for writing." << std::endl;
        return 1;
    }

    outputFile << std::setw(4) << jsonData << std::endl; // 美化输出,每个元素缩进四个空格
    outputFile.close();

    return 0;
}

json.hpp库下载

文章来源:https://blog.csdn.net/cs1395293598/article/details/135206681
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。