Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to properly read a Json string that may be null in some cases? #3135

Closed
TyloowNv opened this issue Nov 11, 2021 · 1 comment
Closed

How to properly read a Json string that may be null in some cases? #3135

TyloowNv opened this issue Nov 11, 2021 · 1 comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@TyloowNv
Copy link

TyloowNv commented Nov 11, 2021

Hello,

I have some json format texts received as server response and would like to use this tool to parse them. The issue is if the value in a string field is optional and not provided from the server side, client side will receive a null rathe than an empty string. This currently throws exceptions while parsing.

For example this is the code where we read the title of a layer.

bh.layers[j].name = js.at(i)["th_layers"].at(j)["layer_title"].get<string>().c_str();

However, in the json format, sometime the server response could be this. And this can be parsed without any issue.
"layer_title": "Fill Material",
But sometimes it becomes this and throws an exception.
"layer_title": null,

Is there a better way of parsing this null and give a default value(like "" for string and 0 for int) rather than using try and catch?

Thanks a lot!

@gregmarr
Copy link
Contributor

js.at(i)["th_layers"].at(j)["layer_title"]

This is what creates the null "layer_title". You need to check if it exists before you try to get its value.

If js is not const then accessing a non-existent object value creates it, while if it is const it's undefined behavior and asserts.

https://json.nlohmann.me/features/element_access/default_value/

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Nov 13, 2021
Repository owner locked and limited conversation to collaborators Nov 13, 2021

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

3 participants