nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.01k stars 6.63k forks source link

a bug about list #3995

Closed linux-rm closed 1 year ago

linux-rm commented 1 year ago

Description

terminating with uncaught exception of type nlohmann::json_abi_v3_11_2::detail::type_error: [json.exception.type_error.305] cannot use operator[] with a string argument with array

code:

#include <iostream>
#include "head/httpC.hpp"
#include <time.h>
#include <ctime>
#include <string>
#include "head/json.hpp"

using namespace nlohmann;
using namespace std;

int main()
{
json data = R"(
{
  "target":0,
  "messageChain":[
    { "type":"Plain", "text":"早上好\n距离中考还剩" },
    { "type":"Plain", "text":"" },
    { "type":"Plain", "text":"天=" },
    { "type":"Plain", "text":"" },
    { "type":"Plain", "text":"小时" }
]
}
)"_json;
/*......*/
time_t now;
/*......*/
now = time(0);
/*......*/
json message = data;
message["messageChain"][1]["text"] = to_string( (1687536000 - now) / (24 * 3600));
message["messageChain"][3]["text"] = to_string( (1687536000 - now) / 3600);
message["messageChain"]["target"] = 951234938;
httpC("/sendGroupMessage", "post", message); // http post
/*......*/
}

Reproduction steps

$ g++ -o test main.cpp
$ ./test
/*......*/
terminating with uncaught exception of type nlohmann::json_abi_v3_11_2::detail::type_error: [json.exception.type_error.305] cannot use operator[] with a string argument with array
[1]    11460 abort      ./test

Minimal code example

message["messageChain"][1]["text"] = to_string(/*num*/);

Compiler and operating system

linux,g++,x86_64(fedora) and arm64(android)

Library version

3.11.2

Validation

linux-rm commented 1 year ago

But this is OK:

std::cout << message["messageChain"][0]["text"] << std::endl;

result:

"早上好\n距离中考还剩"

nlohmann commented 1 year ago

Can you compile with JSON_DIAGNOSTICS? See https://json.nlohmann.me/api/macros/json_diagnostics/

linux-rm commented 1 year ago

info:

terminate called after throwing an instance of 'nlohmann::json_abi_v3_11_2::detail::type_error'
  what():  [json.exception.type_error.305] cannot use operator[] with a string argument with array
nlohmann commented 1 year ago

There should be more information? Did you enable diagnostics?

linux-rm commented 1 year ago

I found the problem, here:

code:

message["messageChain"]["target"] = 951234938;

json:

{
  "target":0,// It is not in "messageChain"
  /*......*/
}
linux-rm commented 1 year ago

Now, It is no problem.