Json: How to check if key existed

Created on 9 Mar 2018  路  8Comments  路  Source: nlohmann/json

Hi to all is there a method to check if the key exist ,

what is the close to

Java JSON

indivFB.has("object_id")

Thanks

question proposed fix

Most helpful comment

Then use find:

if (json_field_data[p]["reactions"]["summary"].find("total_count") != json_field_data[p]["reactions"]["summary"].end())
   // now you can be sure json_field_data[p]["reactions"]["summary"]["total_count"] exists

Alternatively, you could use value and provide a default value (e.g., 0):

totallike = json_field_data[p]["reactions"]["summary"].value("total_count", 0);

All 8 comments

Just like for a map: find().

Hi thanks for the reply but im using iterator

any idea why is causing this problem ?

Value of type 'iterator' (aka 'nlohmann::detail::iter_impl, bool, long long, unsigned long long, double, std::allocator, adl_serializer> >') is not contextually convertible to 'bool'

I would need to see a code example for that.

Hi thanks for time,

The problem i face is that sometimes the json result doesnt have the key so im trying to check for the key

screen shot 2018-03-09 at 5 22 49 pm

When you iterate over an object (which I assume - I have not seen the JSON), doing this with a range for only gives you access to the values, not to the keys. You need to use items() for this.

The exception comes, because you try to assign a number (from ...["total_count"]) to a string (totallike). Try to output ...["total_count"] directly and use a number type for totallike.

Sorry wrong image it should be this

screen shot 2018-03-09 at 5 27 34 pm

Then use find:

if (json_field_data[p]["reactions"]["summary"].find("total_count") != json_field_data[p]["reactions"]["summary"].end())
   // now you can be sure json_field_data[p]["reactions"]["summary"]["total_count"] exists

Alternatively, you could use value and provide a default value (e.g., 0):

totallike = json_field_data[p]["reactions"]["summary"].value("total_count", 0);

Thanks for the library and the help

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sqwunkly picture sqwunkly  路  3Comments

zhishupp picture zhishupp  路  4Comments

moneroexamples picture moneroexamples  路  4Comments

qis picture qis  路  4Comments

bassosimone picture bassosimone  路  3Comments