Javascript JSON annoyance

May 15th, 2007 by mgkimsal Leave a reply »

I was using the what-I-thought-was-the-standard JSON javascript library and ran in to a weird annoyance.  The toJSONString() method will take any arbitrary object or array and serialize the entire thing.  However, the parseJSON() method won’t unserialize recursively.  I ended up with values in my object which were just serialized JSON strings, which I needed to walk through and parseJSON() on individually.  I wish that had been documented.  Hopefully this will serve as some small degree of help for anyone out there looking to use the JSON javascript library.

Share and Enjoy:
  • del.icio.us
  • DZone
  • Facebook
  • Reddit
  • StumbleUpon
  • Digg
  • Simpy
  • Technorati
Advertisement

3 comments

  1. pmuellr says:

    That is annoying. So annoying I wouldn’t use it. How can you tell a regular string from a string with JSON?

    Something I’ve seen people use as an alternative, is to run the JSON string through a regex, to make sure it’s valid and safe, and then just use eval() to evaluate it. Let me see if I can find it … look about 1/2 way down this page: http://tools.ietf.org/html/rfc4627

  2. mgkimsal says:

    I don’t think you would determine the difference. I only happen to know the structure I’m dealing with because I’m dealing with the data on both ends. I did try the eval thing, but had some initial issues with it not working – not sure what caused that but the parseJSON() was easier, till I ran in to the nested issue. If I get some time I may write something which handles it recursively. What you could possibly do is simply try to parseJSON() every element, and if it came back with something, then it worked, otherwise, leave the original value. Too simplistic?

  3. dsipe says:

    Looking at the RFC posted by pmuellr and the parseJSON() source, I don’t really see much difference. parseJSON() is basically stripping out nasty things like “=” and “new” object constructors and then running eval(). You could be running into an issue with toJSONString() rather than parseJSON(). It sounds like you might have an unterminated quote in your JSON–which would be toJSONString()’s fault.

Leave a Reply