I have this string, which is generated by dojo.toJson() function:
{"page":"accommodation task=viewList","language":undefined}
When decoding it with json_decode in php it returns null.
I already figured out that this is caused by the value undefined, but I am not sure if this is to be expected or if it is a bug. Is the above string not valid json? Why can’t php just convert undefined to null?
I am using PHP 5.2.10
Because
undefinedis not valid JSON. JSON doesn’t have the JavaScript concept ofundefined. It does havenull, which is vaguely similar, but the usual thing (for better or worse) is to simply omit properties whose values would beundefined.I’m surprised if Dojo’s
toJsonproduces invalid JSON like that. You might consider using Crockford’sJSON.stringifyinstead. If Dojo’stoJsonis really doing that, I’d report it as a bug to the Dojo team.Update: Apparently someone did report it to them, and they closed it as invalid on the “garbage in, garbage out” theory. Not my project, but that’s just totally not how I would handle properties with
undefinedvalues… I’d omit them or throw an exception.Update 2: As you may know, the ECMAScript 5th edition specification defines a
JSONobject withparseandstringifywhich browsers are adding support for. The specification’s definition ofJSON.stringifysays “undefinedvalues are not rendered” (Section 15.12.3, Note 2) — e.g., the property should be omitted. Perhaps if you point that out to the Dojo team, they’ll rethink their GIGO response to the bug report. Also note @Felix’s comment below: They omit function references, which also can’t be validly represented in JSON, but apply a different rule toundefined.Update 3: Still broken in Dojo 1.6.1. Here’s a live test of v1.6.0, which is the latest on the CDNs. I’ve also tested v1.6.1 and it’s still broken there too. (Not going to post a test page hotlinking to their download section, though, that would be rude.)