How to get the size of a JSON root

599 views
Skip to first unread message

Race

unread,
Aug 16, 2012, 6:12:11 AM8/16/12
to jansso...@googlegroups.com
Hi,

I need to get the size of a JSON root (here the root is 'response') and this is how I do it now:
  str = json_dumps(response, JSON_ENSURE_ASCII);
  if (str)
  {
    reponse_size = strlen(str);
    free(str);
  }
  return (response_size);
Is there a smarter way to get the size of that response ?

/Race

Petri Lehtinen

unread,
Aug 16, 2012, 1:57:03 PM8/16/12
to jansso...@googlegroups.com
If you need to know the length of the serialized JSON text in bytes,
there's no other way. Why would you even need the length if you throw
the actual JSON text away?

Petri

Max Shaffer

unread,
Aug 16, 2012, 2:15:24 PM8/16/12
to jansso...@googlegroups.com
I did come across this problem one time myself. For HTTP HEAD requests it is often useful to know the size of a JSON resource without needing the actual JSON data...
~Max

Graeme Smecher

unread,
Aug 16, 2012, 2:18:48 PM8/16/12
to jansso...@googlegroups.com
Hi all,
Assuming the buffer length is all you need, it's slightly more efficient
to use json_dump_callback() with a function that sums the length of each
callback buffer, instead of completely assembling the results in a
single linear buffer and using strlen(). You can avoid a number of
malloc() and memcpy() calls this way.

As has been suggested, though, it does seem strange to calculate the
length of a JSON object without keeping the serialized version for
later.

cheers,
Graeme

Rasmus Fink

unread,
Aug 16, 2012, 4:23:23 PM8/16/12
to jansso...@googlegroups.com, Graeme Smecher
You're right, it does seem a bit strange :-)

It is because I need to allocate memory for it in a different function,
but that construct might need some reviewing too.

I'll have a look at the json_dump_callback() construct.

Thanks for the pointers and quick reply's.

Cheers
Race
Reply all
Reply to author
Forward
0 new messages