IdleSun's Weblog

January 13, 2010

Single, or Double: That’s the question.

Filed under: JavaScript,JSON — idlesun @ 7:01 pm
Tags: ,

In JavaScript, single quote (‘) and double quote (“) are “kind of” interchangeable. So, the following two lines are all fine:

var helloText1 = 'Hello "Alice"'; 
var helloText2 = "Hello 'Alice'"; 

But, they are not the same in terms of actual string content in each variable because quotation marks are different.
This confusing difference can cause code errors when you try to combine strings to build a JSON object using a parser or eval() function. So, in the following code neither of last two lines will return a JSON object.

var name = "'name':'Alice'";
var phone = '"phone":"111-222-3333"';
var contact1 = eval("{" + name + "," + phone + "}");      // error
var contact2 = JSON.parse("{" + name + "," + phone + "}");   // error

Note that json2.js is used for JSON parser. Anyway, it is because different types of quotation marks can not be mixed in a string that represents a JSON object. That means the following code is fine:

var contact = JSON.parse("{'name':'Alice','phone':'111-222-3333'}");
var jsonText = JSON.stringify(contact);

One thing to note is that re-converted jsonText will contain double(“) for string quotation mark instead of single (‘). So, it will be like this if you check the content of jsonText:

{"name":"Alice","phone":"111-222-3333"}

As I mentioned in the beginning, it is confusing and can cause code errors. One way to avoid is to use one type of quotation mark consistently for JSON handling. My recommendation is “single outside and double inside“, which is like this:

var jsonContact = '{"name":"Alice","phone":"111-222-3333"}';

This way, it will be less confusing when you compare original input string with re-converted string from a parsed JSON object.
However, it is also important to understand the differences between quotation marks as wrapper code of string literal and quotation marks just as characters in a string. The confusing came from the thing that a quotation mark as character becomes wrapper code when string is eval()ed or parsed.
To understand better, take a look at the following code that shows how JSON object can be directly defined various ways including mixing quotation marks:

var contact1 = {"name":"Alice","phone":"111-222-3333"};
var contact2 = {'name':'Alice','phone':'111-222-3333'}; 
var contact3 = {'name':"Alice","phone":'111-222-3333'}; 

Note that all three lines are fine and create basically the same JSON object. So, if you converts all three objects to strings back, those strings will be the same with double quotation mark. Again, mixing is not a good coding practice and using double inside seems better and less confusing.

Blog at WordPress.com.