nlohmann::json组包报错:[type_error.305] cannot use operator[] with a string argument with array

文章讨论了在使用nlohmann::json库时遇到的类型错误,即尝试用字符串键访问数组导致的异常。通过分析代码,指出了问题出现在尝试用字符串对数组进行索引,而非对对象。提供了正确访问嵌套结构的示例,并展示了两个具体的报错场景及相应的修正方法。
摘要由CSDN通过智能技术生成

大致分析

Exception caught: [json.exception.type_error.305] cannot use operator[] with a string argument with array

这个错误是因为你试图使用operator[]操作符来访问一个nlohmann::json对象中的一个字符串键值,但是该对象实际上是一个数组,而不是一个对象。

例如,如果你有一个JSON数组:

[
  {
    "name": "Alice",
    "age": 25
  },
  {
    "name": "Bob",
    "age": 30
  }
]

你可以使用operator[]操作符来访问数组中的元素,如下所示:

nlohmann::json j = /* JSON数组 */;
nlohmann::json alice = j[0]; // 访问数组中的第一个元素

但是,如果你尝试使用一个字符串键值来访问该数组,就会出现上述错误:

nlohmann::json j = /* JSON数组 */;
nlohmann::json alice = j["name"]; // 错误:不能使用字符串键值来访问数组

如果你想访问数组中的元素的某个属性,你需要先访问该元素,然后再使用operator[]操作符来访问该属性,如下所示:

nlohmann::json j = /* JSON数组 */;
nlohmann::json alice = j[0]; // 访问数组中的第一个元素
std::string name = alice["name"]; // 访问该元素的"name"属性

报错场景1

在这里插入图片描述
我的请求body和解析代码:

{
    "CameraRegion": {
        "AlgorithmName": "wear",
        "CameraID": "12679465827b4014a187a17f3f79777a",
        "CommonRegions": [
            [
                {
                    "x": 0.083551,
                    "y": 0.121602
                },
                {
                    "x": 0.267624,
                    "y": 0.121602
                },
                {
                    "x": 0.267624,
                    "y": 0.424893
                },
                {
                    "x": 0.083551,
                    "y": 0.424893
                }
            ],
            [
                {
                    "x": 0.065274,
                    "y": 0.599428
                },
                {
                    "x": 0.254569,
                    "y": 0.599428
                },
                {
                    "x": 0.254569,
                    "y": 0.886981
                },
                {
                    "x": 0.065274,
                    "y": 0.886981
                }
            ]
        ],
        "SubAlgoRegions": [
            {
                "Regions": [
                    [
                        [
                            {
                                "x": 0.565065,
                                "y": 0.883262
                            },
                            {
                                "x": 0.275065,
                                "y": 0.583262
                            },
                            {
                                "x": 0.375065,
                                "y": 0.583262
                            },
                            {
                                "x": 0.475065,
                                "y": 0.533262
                            }
                        ],
                        [
                            {
                                "x": 0.4547,
                                "y": 0.422604
                            },
                            {
                                "x": 0.3547,
                                "y": 0.122604
                            },
                            {
                                "x": 0.4547,
                                "y": 0.122604
                            },
                            {
                                "x": 0.4547,
                                "y": 0.077396
                            }
                        ]
                    ],
                    [
                        {
                            "x": 0.504569,
                            "y": 0.164521
                        },
                        {
                            "x": 0.575718,
                            "y": 0.164521
                        },
                        {
                            "x": 0.575718,
                            "y": 0.359084
                        },
                        {
                            "x": 0.504569,
                            "y": 0.359084
                        }
                    ]
                ],
                "SubAlgoName": "noWithHelmet"
            }
        ]
    }
}
// This function will parse json region. camera regions json  --> ky_ai_camera_region struct
// if the process is successful, it return ture, else return false.
//@para [in]   json: json contains camera regions to be parsed
//@para [out]  camera_region: std::vector<std::vector<ky_ai_pos>> regions struct
bool ky_ai_parse_json_camera_region(nlohmann::json &json, ky_ai_camera_region &camera_region)
{

	try // arnold add try...catch 20221020
	{
		camera_region.CameraID = json["CameraRegion"]["CameraID"];
		camera_region.AlgorithmName = json["CameraRegion"]["AlgorithmName"];
		ky_ai_parse_json_region(json["CameraRegion"]["CommonRegions"], camera_region.CommonRegions);
		for (auto json_algo_region : json["CameraRegion"]["SubAlgoRegions"])
		{
			std::string sub_algo_name = json_algo_region["SubAlgoName"];
			std::vector<std::vector<ky_ai_pos>> regions;
			ky_ai_parse_json_region(json_algo_region["Regions"], regions);
			camera_region.SubAlgoRegions.push_back({sub_algo_name, regions});
		}
	}
	catch (nlohmann::json::exception &e)
	{
		// printf("ky_ai_parse_json parse fail! reason: [%s]\n", e.what());
		// KY_AI_LOG("ky_ai_parse_json parse fail! reason: [", e.what(), "]\n");	// origin
		KY_AI_LOG("ky_ai_parse_json_camera_region ky_ai_parse_json parse fail! reason: [", e.what(), "]\n");	//arnold modified 20230419
		return false;
	}

	return true;
}
// This function will parse json region. regions json  --> regions struct
// if the process is successful, it return ture, else return false.
//@para [in]   json: json contains regions to be parsed
//@para [out]  regions: std::vector<std::vector<ky_ai_pos>> regions struct
bool ky_ai_parse_json_region(nlohmann::json &json, std::vector<std::vector<ky_ai_pos>> &regions)
{
	for (auto json_region : json)
	{
		std::vector<ky_ai_pos> region;
		for (auto json_pos : json_region)
		{
			ky_ai_pos pos;
			pos.x = json_pos["x"];
			pos.y = json_pos["y"];
			region.push_back(pos);
		}
		regions.push_back(region);
	}
	return true;
}

问题产生原因

貌似是请求body写错了,多了个[]

在这里插入图片描述

正确的body:

{
    "CameraRegion": {
        "AlgorithmName": "wear",
        "CameraID": "12679465827b4014a187a17f3f79777a",
        "CommonRegions": [
            [
                {
                    "x": 0.083551,
                    "y": 0.121602
                },
                {
                    "x": 0.267624,
                    "y": 0.121602
                },
                {
                    "x": 0.267624,
                    "y": 0.424893
                },
                {
                    "x": 0.083551,
                    "y": 0.424893
                }
            ],
            [
                {
                    "x": 0.065274,
                    "y": 0.599428
                },
                {
                    "x": 0.254569,
                    "y": 0.599428
                },
                {
                    "x": 0.254569,
                    "y": 0.886981
                },
                {
                    "x": 0.065274,
                    "y": 0.886981
                }
            ]
        ],
        "SubAlgoRegions": [
            {
                "Regions": [
                    [
                        {
                            "x": 0.565065,
                            "y": 0.883262
                        },
                        {
                            "x": 0.275065,
                            "y": 0.583262
                        },
                        {
                            "x": 0.375065,
                            "y": 0.583262
                        },
                        {
                            "x": 0.475065,
                            "y": 0.533262
                        }
                    ],
                    [
                        {
                            "x": 0.4547,
                            "y": 0.422604
                        },
                        {
                            "x": 0.3547,
                            "y": 0.122604
                        },
                        {
                            "x": 0.4547,
                            "y": 0.122604
                        },
                        {
                            "x": 0.4547,
                            "y": 0.077396
                        }
                    ],
                    [
                        {
                            "x": 0.504569,
                            "y": 0.164521
                        },
                        {
                            "x": 0.575718,
                            "y": 0.164521
                        },
                        {
                            "x": 0.575718,
                            "y": 0.359084
                        },
                        {
                            "x": 0.504569,
                            "y": 0.359084
                        }
                    ]
                ],
                "SubAlgoName": "noWithHelmet"
            }
        ]
    }
}

报错场景2

在这里插入图片描述

原因:

json组包少括号了

右边是对的

在这里插入图片描述

附上我的测试代码

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

int main()
{
    nlohmann::json incomingJson = R"(
        {
            "cameraId": "ced83c892f3f41acabd530e68d36a4ab",
            "engineName": "personBehavior",
            "frameInfo": {
                "displayTime": 1681907076153,
                "frameId": 1681907076153,
                "image": "1986,01fff58abd123b"
            },
            "name": "noWithHelmet",
            "objects": [
                {
                    "rect": {
                        "h": 206,
                        "w": 53,
                        "x": 521,
                        "y": 896
                    },
                    "subImage": "",
                    "trackId": 0
                }
            ],
            "params": {
                "curValue": "0",
                "desc": "未带安全帽告警<br>报警定义:<br>未带安全帽-【personBehavior-noWithHelmet】",
                "name": "helmetWear",
                "objUrl": "1967,01fff449030ded",
                "targetValue": "0",
                "type": 1
            },
            "sessionid": "ced83c892f3f41acabd530e68d36a4ab"
        }
    )"_json;

    nlohmann::json outgoingJsonAlarm; // 定义 outgoingJsonAlarm
    nlohmann::json outgoingJsonTarget;
    std::string SubAlgoChName = "event_id"; // 定义 SubAlgoChName
    std::string AlarmTitle = "alarm_title"; // 定义 AlarmTitle
    std::string Desc = "alarm_desc";        // 定义 Desc
    int objNum = 10;                        // 定义 objNum

    outgoingJsonAlarm =
        {{"alarmInfo",
          {{"cameraID", incomingJson["cameraId"]},
           {"eventID", SubAlgoChName},
           {"alarmType", "start"},
           {"urlType", "pic"},
           {"url", incomingJson["frameInfo"]["image"]},
           {"kyTimeStamp", incomingJson["frameInfo"]["displayTime"]},
           {"alarmTitle", AlarmTitle},
           {"alarmDesc", Desc},
           {"objNum", objNum},
           {"tgtList",
            {{"tgtNUM", objNum},
             {"tgtCoords", nlohmann::json::array()}}}}}};

    outgoingJsonTarget =
        {{"targetInfo",
          {{"cameraID", incomingJson["cameraId"]},
           {"timeStamp", incomingJson["frameInfo"]["displayTime"]},
           {"url", incomingJson["frameInfo"]["image"]},
           {"tgtList",
            {{"tgtNUM", objNum},
             {"tgtCoords", nlohmann::json::array()}}}}}};

    for (const auto &obj : incomingJson["objects"])
    {
        nlohmann::json tgtCoord =
            {{"classId", 0},
             {"rect",
              {{"point",
                {{"x", obj["rect"]["x"]},
                 {"y", obj["rect"]["y"]}}},
               {"width", obj["rect"]["w"]},
               {"height", obj["rect"]["h"]}}}};

        outgoingJsonAlarm["alarmInfo"]["tgtList"]["tgtCoords"].push_back(tgtCoord);
        // outgoingJsonTarget["targetInfo"]["tgtList"]["tgtCoords"].push_back(tgtCoord);   // 报错:terminate called after throwing an instance of 'nlohmann::detail::type_error'; what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array; Aborted (core dumped)
        outgoingJsonTarget["targetInfo"]["tgtList"]["tgtCoords"].push_back(tgtCoord);
    }

    std::cout << outgoingJsonAlarm.dump(4) << std::endl;
    std::cout << outgoingJsonTarget.dump(4) << std::endl;

    return 0;
}

编译:

g++ test.cpp

运行:

./a.out

正常运行打印结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dontla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值