JSON vs. JavaScript

kick it on DotNetKicks.com

JSON is not JavaScript (nor a JavaScript “subset”)

JSON is not only a syndication format (e.g. an alternative to XML), it is a language-independent data interchange format.

As such, while JSON objects are based on the JavaScript object literal, they are not the same. In fact, JSON objects can be invalid as JavaScript objects. Therefore, JSON should be transformed to JavaScript-compliant JSON before feeding Ajax or JavaScript applications.

This flexibility on the part of JSON increases its extensibility as an interchange format. Although JSON makes a strong competitor to XML for Ajax applications, it is meant to be suitable for other mediums as well (hence JSON RPC).

How they are Different—Property Names

Their difference is in what is permissible for property names, defined by the ECMA Standard for JavaScript, and JSON member (property) names, defined by RFC 4627.

JavaScript requires property names to start with an underscore (_), letter, or dollar sign ($), and contain only alphanumeric characters, underscores, and dollar signs:

var chris = {
	lastName: "O'Brien",
	_city: "Seattle",
	income$: "Dollar sign"
};
alert("Chris lives in " + chris._city);

JSON property names, on the other hand, may contain any Unicode characters, provided proper escaping of control characters. For example, the object defined in by the { } literal below is valid JSON, yet cannot be used to create an object in JavaScript.

// throws an Error
var impossible = {
	"411": "yohoho.com",
	"xmlns:x": "Invalid character",
	"Company name": "Spaces",
	"": "Zero-length string"
};

Because JSON property names can contain spaces and JavaSript’s cannot, JSON property names must be encapsulated in quotations. In JavaScript, encapsulating property names is optional. Quotations also make an empty zero- or variable-length property name possible in JSON.

Reserved Words

Furthermore, JavaScript (like all well-adopted languages) has reserved words. These are words that have special meaning and cannot be used as property names. Below is a table of reserved words. Words without asterisks are reserved keywords and words with asterisks are words reserved for future use.These can be found in ECMA-262 under heading 7.5.

abstract*
boolean*
break
byte*
case
catch
char*
class*
const*
continue
debugger*
default
delete
do
double*
class*
const*
continue
debugger*
default
delete
do
double*
else
enum*
export*
extends*
final*
finally
float*
for
function
goto*
if
implements*
import*
in
instanceof
int*
interface*
long*
native*
new
package*
private*
protected*
public*
return
short*
static*
switch
super*
synchronized*
this
throw
throws*
transient*
try
typeof
volatile*

Ordered Steps for Transforming JSON for JavaScript

To guarantee that JSON data can be consumed by JavaScript, like so:

var obj = eval("(" + jsonString + ")");

…the operations below need to be performed on a string of JSON data. This will ensure that the JSON data is JavaScript-compliant.

  1. Remove or replace any spaces in property names.
  2. Remove or replace the first character in the name of a property if it is not an underscore, letter, or dollar sign.
  3. Remove or replace any non-alphanumeric character, save for underscores and dollar signs.
  4. Replace property names that are reserved words in JavaScript.
  5. If a property name is an empty, zero-length string, replace it with a valid JavaScript property name.
  6. Optionally, quotations around property names may be removed.

† Quotations and control characters must be escaped. Check out the RFC for details.

9 Comments »

  1. […] another link which also describes JSON in a concise form – and has a funny picture Also, this post describes some of the exception cases where JSON is not actually legal JS (JS is a little more […]

  2. Ian said

    Erm, I don’t understand this post.

    You know that Javascript allows quoted keys for its objects too, right? So this is fine in javascript:

    var foo = {“new”:1, “var”: 2, “break”:3};

    The only thing about this format is that you can’t use Javascript’s syntactic sugar of property access, but the Javascript is valid and you can still use it fine.

    RFC 4627 explicitly says property names in JSON must be strings. It also says that JSON is a subset of Javascript.

    “In fact, JSON objects can be invalid as JavaScript objects.”

    Can you give an example of a piece of valid JSON that wouldn’t be valid Javascript?

  3. Chris said

    It doesn’t sound like to me you actually read the post. Valid JSON that’s not valid JavaScript is right there plain as day:

    { “411”: “yohoho.com”, “xmlns:x”: “Invalid character”, “Company name”: “Spaces”,””: “Zero-length string” }\

    Valid JSON. Invalid JavaScript.

  4. Ian said

    Okay, (assuming your smart quotes are intended to be regular quotes) that’s what I thought you were getting at.

    In the context of something like:

    var foo = {…};

    your example is perfectly valid and legal Javascript, it conforms to the ECMA-262 (BNF in section 11.1.5), and it runs on the major JS platforms: I just tested in SpiderMonkey, Rhino, v8, and Futhark, all accept it fine and allow me to manipulate the elements in the object after initialization.

    • Ian said

      I just re-read ECMA 262 and RFC 4627 side by side, and the grammar specifications confirm that JSON is, in fact, a strict subset of Javascript (even down to the unicode and escape sequences they both accept in their strings).

      RFC 4627 explicitly says this in its introduction, of course, but that is probably best treated as non-normative (4627 is not a specification, in any case). The detailed production rules confirm it though.

      I came across your blog post because I had a client who insisted that JSON wasn’t a subset of Javascript, and hunting around the source of this urban myth seemed to be your blog. Most other sources (including the JSON site, wikipedia, etc) correctly state that JSON is a subset of Javascript.

  5. Chris said

    LISTEN HERE FUDGEPACKER I KNOW EVERYTHING AND YOU MEAN NOTHING. END OF STORY NOW STFU.

  6. Ian said

    Ah, different Chris. Didn’t spot that first time out.

    Funny.

    • Jannick said

      Hahahah, Chris got mad…

  7. GimmeFever said

    Having to make sure the JSON string is a valid JS code somehow implies that the string comes from an external source.

    Calling eval() blindly on such a beast creates huge security holes. For production environments you should better use a proper JSON parser.

RSS feed for comments on this post · TrackBack URI

Leave a reply to Ian Cancel reply