Javascript JSON annoyance
May 15, 2007
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.
Did you like this post? Buy me a hot chocolate!
Posted in




May 15th, 2007 at 6:07 pm
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
May 15th, 2007 at 9:26 pm
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?
May 18th, 2007 at 2:51 pm
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.