json_unpack - how to extract values that can be string or null type

106 views
Skip to first unread message

spd...@gmail.com

unread,
Mar 27, 2019, 8:22:01 PM3/27/19
to Jansson users
Hello all,

I'd like to use json_unpack to extract foo's value for both of the below JSON data.  Problem is, I don't know a format string that will handle both cases.  Please help me know the best approach - thanks.

{"foo": "foostr"} - works with format string "s:s" - fails with "s:n"
{"foo": null} - works with format string "s:n" - fails with "s:s"

I was hoping there is some format string which combines 's' and 'n' so I can get "foostr" for the 1st case and a NULL pointer returned for 2nd case.  But, I couldn't find it.

From my online searching, it seems one option is to avoid json_unpack if string and null are possible values, and instead manually extract each field (see below), but I'm wondering for a simpler approach since there are many JSON variables to handle.

Here's my current option (pardon my pseudocode):
   json_t * pObj = json_object_get (root, "foo");
   if (!pObj) {return ERROR};
   if (json_is_null (pObj) {return NULL;}
   else if (json_is_string(pObj)) {return json_string_value(pObj);}
   else {return ERROR;}

Thanks for your help.

Best regards,
Shaun

Petri Lehtinen

unread,
Mar 28, 2019, 11:36:02 PM3/28/19
to jansso...@googlegroups.com
Hi Shaun,

Unfortunately there's currently no support for this. Since you have multiple values you need to check, you could use the "o" format to extract them all in a single call to json_unpack(), but after that, manual checking for null is required.

Petri
--
--
Jansson users mailing list
jansso...@googlegroups.com
http://groups.google.com/group/jansson-users
---
You received this message because you are subscribed to the Google Groups "Jansson users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jansson-user...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

spd...@gmail.com

unread,
Mar 29, 2019, 1:14:00 AM3/29/19
to Jansson users
Hi Petri,

Thanks for the quick reply.  I'll check this approach.  Not sure if there's a chance, but I'll put an issue in the tracker to help handle servers that mix strings and nulls in their JSON values.  I can see how returning NULL could be problematic from a segfault point of view, but it'd currently be useful for me (n.b. not sure about other users, how common this case is, etc.).  Regardless, thanks so much!

Best regards,
Shaun
Reply all
Reply to author
Forward
0 new messages