akheron / jansson

C library for encoding, decoding and manipulating JSON data
http://www.digip.org/jansson/
Other
3.02k stars 807 forks source link

json_dumps function not working correctly #227

Open akshaydorwat opened 9 years ago

akshaydorwat commented 9 years ago

I have been using this library for a while. When i was using json_dumps function it was throwing garbage in the end of buffer. I reduced my JSON_INDENT from 4 to 2. it got fixed.

In another case i have two 2 string items in the array (confirmed with json_array_size). when i do

json_dumps(json_array_get(json_ret, 1), JSON_INDENT(2));

It returning NULL value. I am using latest version.

akheron commented 9 years ago

You need to use the JSON_ENCODE_ANY flag with json_dumps() to encode a plain string. RFC 4627 (the old JSON spec) says that objects and arrays are the only valid top-level values.

This will requirement will probably be lifted in the future because RFC 7159 (the new spec) doesn't have this requirement anymore.

What comes to garbage produced by json_dumps(), I'd like to have more information. Could you post an example that reproduces the issue?

nfnty commented 9 years ago

I'm having the same problem trying to print a json object with json_dumpf(). I've tested 0-5. 0-3 works fine, 4-5 randomly produces garbled output. Happens about 1 in 5 times.

Running with valgrind --leak-check=full --show-leak-kinds=all fixes the garbled output, but no errors are logged.

Output and diff: https://gist.github.com/nfnty/2db2bf1de27e1bae2872

Code: https://github.com/nfnty/bspwm/blob/json/messages.c#L667-L709 https://github.com/nfnty/bspwm/blob/json/query.c#L142-L353

akheron commented 9 years ago

The dump_indent function that writes the indentation whitespace is here: https://github.com/akheron/jansson/blob/master/src/dump.c#L46-L69. I don't see how it could output garbage, unless the static whitespace buffer has been overwritten because of a buffer overrun.

You could add a guard in the beginning of dump_indent to check whether whitespace contains 32 spaces. But even if it doesn't, it might be hard to find out why.