Rectangle 27 552

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 1064

JSON-js - JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);
JSON.parse
var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

Good point @Mark0978. Just by way of explanation, the arguments to JSON.stringify are explained here. I've not seen a good usecase for the second parameter yet, but the last parameter is quite useful: it indicates how many spaces to use to indent with when formatting the JSON string.

Check the issues before using this solution: [github.com/douglascrockford/JSON-js/pull/13] Maybe safer is tweak this code create some JSON2 object and use it regardless the JSON support in the browser.

JSON.stringify(obj, function(key, val) { if (val instanceof SVGSVGElement) {return val.xml || new XMLSerializer().serializeToString(val);} return val;})

Crockford's code wasn't playing nice with some more complex jQuery selectors. When I commented out the Object.prototype modifications at the bottom of the file, it worked as expected.

I actually prefer JSON3. It has AMD/requireJS support plus it does not use eval which Crockform himself mentioned as "evil". github.com/bestiejs/json3

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Serializing to JSON in jQuery - Stack Overflow

javascript jquery ajax json serialization
Rectangle 27 1061

JSON-js - JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);
JSON.parse
var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

Newer browsers support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.

Good point @Mark0978. Just by way of explanation, the arguments to JSON.stringify are explained here. I've not seen a good usecase for the second parameter yet, but the last parameter is quite useful: it indicates how many spaces to use to indent with when formatting the JSON string.

Check the issues before using this solution: [github.com/douglascrockford/JSON-js/pull/13] Maybe safer is tweak this code create some JSON2 object and use it regardless the JSON support in the browser.

JSON.stringify(obj, function(key, val) { if (val instanceof SVGSVGElement) {return val.xml || new XMLSerializer().serializeToString(val);} return val;})

Crockford's code wasn't playing nice with some more complex jQuery selectors. When I commented out the Object.prototype modifications at the bottom of the file, it worked as expected.

I actually prefer JSON3. It has AMD/requireJS support plus it does not use eval which Crockform himself mentioned as "evil". github.com/bestiejs/json3

javascript - Serializing to JSON in jQuery - Stack Overflow

javascript jquery ajax json serialization
Rectangle 27 552

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 548

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 548

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 11

+1 for reminding the community to keep an eye out for dupes.

jquery - Javascript - Json or html? - Stack Overflow

javascript jquery asp.net-mvc ajax json
Rectangle 27 221

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

That would be a good thing, escaping just </. Though JSON is not often embedded in script tags anyway.

JSON needs to be replaced because a particular implementation of a JSON serializer outputs some JSON that (while being entirely valid JSON) has some extra characters so it can also be dropped into an HTML script element as a JS literal?! That isn't so much throwing the baby out with the bathwater as throwing the baby out because someone bought him a set of water wings.

What I don't get, is why a JSON serializer would even care where the JSON ends up. On a web page, in an HTTP request, whatever. Let the final renderer do additional encoding, if it needs it.

@DanRoss And it can. Escaping / is not required, it is allowed, to ease the use of JSON. If you don't want to escape /, then don't.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - JSON: why are forward slashes escaped? - Stack Overflow

javascript json
Rectangle 27 216

JSON doesn't require you to do that, it allows you to do that. It also allows you to use "\u0061" for "A", but it's not required. Allowing \/ helps when embedding JSON in a <script> tag, which doesn't allow </ inside strings, like Seb points out.

Some of Microsoft's ASP.NET Ajax/JSON API's use this loophole to add extra information, e.g., a datetime will be sent as "\/Date(milliseconds)\/". (Yuck)

That would be a good thing, escaping just </. Though JSON is not often embedded in script tags anyway.

JSON needs to be replaced because a particular implementation of a JSON serializer outputs some JSON that (while being entirely valid JSON) has some extra characters so it can also be dropped into an HTML script element as a JS literal?! That isn't so much throwing the baby out with the bathwater as throwing the baby out because someone bought him a set of water wings.

What I don't get, is why a JSON serializer would even care where the JSON ends up. On a web page, in an HTTP request, whatever. Let the final renderer do additional encoding, if it needs it.

@DanRoss And it can. Escaping / is not required, it is allowed, to ease the use of JSON. If you don't want to escape /, then don't.

javascript - JSON: why are forward slashes escaped? - Stack Overflow

javascript json
Rectangle 27 112

Some modern browsers have support for parsing JSON into a native object:

var var1 = '{"cols": [{"i" ....... 66}]}';
var result = JSON.parse(var1);

For the browsers that don't support it, you can download json2.js from json.org for safe parsing of a JSON object. The script will check for native JSON support and if it doesn't exist, provide the JSON global object instead. If the faster, native object is available it will just exit the script leaving it intact. You must, however, provide valid JSON or it will throw an error you can check the validity of your JSON with http://jslint.com or http://jsonlint.com.

javascript - JSON string to JS object - Stack Overflow

javascript jquery json jsonp getjson
Rectangle 27 3

I'd lean towards JSON myself. The reason is that JSON affords you the flexibility to bring back different data. e.g.

You might bring back 100 results, AND some metadata about what those results are (keywords, grouping, etc.) AND info about how many more results are available, how fresh the results are, paging info...

With pure HTML returned you limit further options to do anything other than update the HTML content of a container.

i would update the list of messages in a chat

jquery - Javascript - Json or html? - Stack Overflow

javascript jquery asp.net-mvc ajax json
Rectangle 27 367

Making sure the JSON never executes

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any informations from pages on an other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img>tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as Javascript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as Javascript, not at the time it's parsed.

There are multiple counter measures:

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as Javascript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

for(;;);

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

This is OWASP recommended way to protect from JSON hijacking, and is the less intrusive one.

Similarly to the the previous counter-measures, it makes sure that the JSON is never executed as Javascript.

A valid JSON object, when not enclosed by anything, is not valid in Javascript:

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid Javascript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid Javascript, and knowing the object is empty may itself be valuable information.

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

Google's way requires client library in order for it to support automatic de-serialization, and can be considered to be safer with regard to browser bugs.

OWASP recommendation is interesting because of its simplicity. Anyone know a reason Google's way is more secure?

I believe it isn't more secure in any way. Providing OWASP here seems a good enough reason for +1.

What browsers in 2014 let you replace Array or Object constructor?

It may be worth noting why returning an object literal fails the script tag or eval function. The braces {} can be interpreted as either a block of code or an object literal, and by itself, JavaScript prefers the former. As a block of code it is, of course, invalid. By this logic, I cant see any foreseeable changes in future browser behaviour.

Bad code is not enough becaues an attacker can also hijack the script-error hander of the browser (window.onerror) I'm not sure what is the behavior of onerror with syntax errors. I guess Google were unsure as well.

javascript - Why does Google prepend while(1); to their JSON responses...

javascript json ajax security
Rectangle 27 365

Making sure the JSON never executes

It prevents disclosure of the response through JSON hijacking.

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any informations from pages on an other domain (unless explicitly allowed).

In theory, Google's JSON responses are protected by the Same Origin Policy: pages from one domain cannot get any informations from pages on an other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img>tag, but it can't get any information about the result (headers, contents).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img>tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as Javascript in an attacker's controlled environment. If the attacker can replace the Array or Object contructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Except that when using a script tag to request JSON content, the JSON is executed as Javascript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as Javascript, not at the time it's parsed.

Note that this happens at the time the JSON is executed as Javascript, not at the time it's parsed.

There are multiple counter measures:

There are multiple counter measures:

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as Javascript.

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as Javascript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

for(;;);

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

This is OWASP recommended way to protect from JSON hijacking, and is the less intrusive one.

Similarly to the the previous counter-measures, it makes sure that the JSON is never executed as Javascript.

A valid JSON object, when not enclosed by anything, is not valid in Javascript:

This is OWASP recommended way to protect from JSON hijacking, and is the less intrusive one.

Similarly to the the previous counter-measures, it makes sure that the JSON is never executed as Javascript.

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

A valid JSON object, when not enclosed by anything, is not valid in Javascript:

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid Javascript, while still being valid JSON.

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however.

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid Javascript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid Javascript, and knowing the object is empty may itself be valuable information.

Google's way requires client library in order for it to support automatic de-serialization, and can be considered to be safer with regard to browser bugs.

OWASP recommendation is interesting because of its simplicity. Anyone know a reason Google's way is more secure?

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

I believe it isn't more secure in any way. Providing OWASP here seems a good enough reason for +1.

What browsers in 2014 let you replace Array or Object constructor?

Google's way requires client library in order for it to support automatic de-serialization, and can be considered to be safer with regard to browser bugs.

How would the OWASP method prevent people from simply using a JSONP method to get the data? It seems to me Google's method prevents this by not serving a valid JSON object, whereas the OWASP method says to use a valid JSON object so it can't be executed as javascript.

OWASP recommendation is interesting because of its simplicity. Anyone know a reason Google's way is more secure?

JSONP requires the server to participate, and since the point of JSONP is to allow cross-domain access to the data in question, I don't think the server would be concerned with preventing cross-domain access to that data.

I believe it isn't more secure in any way. Providing OWASP here seems a good enough reason for +1.

What browsers in 2014 let you replace Array or Object constructor?

It may be worth noting why returning an object literal fails the script tag or eval function. The braces {} can be interpreted as either a block of code or an object literal, and by itself, JavaScript prefers the former. As a block of code it is, of course, invalid. By this logic, I cant see any foreseeable changes in future browser behaviour.

Bad code is not enough becaues an attacker can also hijack the script-error hander of the browser (window.onerror) I'm not sure what is the behavior of onerror with syntax errors. I guess Google were unsure as well.

javascript - Why does Google prepend while(1); to their JSON responses...

javascript json ajax security
Rectangle 27 365

Making sure the JSON never executes

It prevents disclosure of the response through JSON hijacking.

In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any informations from pages on an other domain (unless explicitly allowed).

An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...> or <img>tag, but it can't get any information about the result (headers, contents).

Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.

Except that when using a script tag to request JSON content, the JSON is executed as Javascript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.

Note that this happens at the time the JSON is executed as Javascript, not at the time it's parsed.

There are multiple counter measures:

By placing a while(1); statement before the JSON data, Google makes sure that the JSON data is never executed as Javascript.

Only a legitimate page could actually get the whole content, strip the while(1);, and parse the remainder as JSON.

for(;;);

Similarly, adding invalid tokens before the JSON, like &&&START&&&, makes sure that it is never executed.

This is OWASP recommended way to protect from JSON hijacking, and is the less intrusive one.

Similarly to the the previous counter-measures, it makes sure that the JSON is never executed as Javascript.

A valid JSON object, when not enclosed by anything, is not valid in Javascript:

eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}

So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid Javascript, while still being valid JSON.

As noted by @hvd in the comments, the empty object {} is valid Javascript, and knowing the object is empty may itself be valuable information.

The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).

Google's way requires client library in order for it to support automatic de-serialization, and can be considered to be safer with regard to browser bugs.

OWASP recommendation is interesting because of its simplicity. Anyone know a reason Google's way is more secure?

I believe it isn't more secure in any way. Providing OWASP here seems a good enough reason for +1.

What browsers in 2014 let you replace Array or Object constructor?

It may be worth noting why returning an object literal fails the script tag or eval function. The braces {} can be interpreted as either a block of code or an object literal, and by itself, JavaScript prefers the former. As a block of code it is, of course, invalid. By this logic, I cant see any foreseeable changes in future browser behaviour.

Bad code is not enough becaues an attacker can also hijack the script-error hander of the browser (window.onerror) I'm not sure what is the behavior of onerror with syntax errors. I guess Google were unsure as well.

javascript - Why does Google prepend while(1); to their JSON responses...

javascript json ajax security
Rectangle 27 237

Parsing a string containing JSON data

You can use JSON.parse()

You should be able to use the JSON object on any ECMAScript 5 compatible JavaScript implementation. And V8, upon which Node.js is built is one of them.

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);

You'll have to do some file operations with fs module.

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
var obj = require('path/to/file.json');

But, I do not recommend this for several reasons:

  • require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs.
  • If your file does not have a .json extension, require will not treat the contents of the file as JSON.
  • require is synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parse with fs.readFile.
JSON.parse

If you are reading large number of .json files, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the jsonfile module.

var jf = require('jsonfile');
jf.readFile('/path/to/file.json', function(err, obj) {
  // obj contains JSON data
});
var obj = jf.readFileSync('/path/to/file.json');

If the JSON content is streamed over the network, you need to use a streaming JSON parser. Otherwise it will tie up your processor and choke your event loop until JSON content is fully streamed.

If you are unsure if whatever that is passed to JSON.parse() is valid JSON, make sure to enclose the call to JSON.parse() inside a try/catch block. A user provided JSON string could crash your application, and could even lead to security holes. Make sure error handling is done if you parse externally-provided JSON.

and could even lead to security holes

@natario: We are talking about server-side JS here. Suppose someone is parsing user-supplied JSON. If the assumption is that the JSON is always well formed, an attacker can send some malformed JSON to trigger an error, which if spilled to the client side, may reveal vital information about the system. Or if the JSON was both malformed and contained some text with <script>..., and the error is spilled to the client side, you have an XSS bug right there. Therefore IMO it's important to handle JSON errors right where you parse it.

@Krumia: Are you talking about security holes in user-supplied JSON that was added via the require statement? I think var config = require(jsonFile); will be literally as "user-supplied" as any other source code, correct? It would be handled at source compile-time.

@NickSteele: However, I changed "this is not recommended" to "I do not recommend". I hope you are happy now.

javascript - How to parse JSON using Node.js? - Stack Overflow

javascript json node.js
Rectangle 27 234

Parsing a string containing JSON data

You can use JSON.parse()

You should be able to use the JSON object on any ECMAScript 5 compatible JavaScript implementation. And V8, upon which Node.js is built is one of them.

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);

You'll have to do some file operations with fs module.

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
var obj = require('path/to/file.json');

But, I do not recommend this for several reasons:

  • require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs.
  • If your file does not have a .json extension, require will not treat the contents of the file as JSON.
  • require is synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parse with fs.readFile.
JSON.parse

If you are reading large number of .json files, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the jsonfile module.

var jf = require('jsonfile');
jf.readFile('/path/to/file.json', function(err, obj) {
  // obj contains JSON data
});
var obj = jf.readFileSync('/path/to/file.json');

If the JSON content is streamed over the network, you need to use a streaming JSON parser. Otherwise it will tie up your processor and choke your event loop until JSON content is fully streamed.

If you are unsure if whatever that is passed to JSON.parse() is valid JSON, make sure to enclose the call to JSON.parse() inside a try/catch block. A user provided JSON string could crash your application, and could even lead to security holes. Make sure error handling is done if you parse externally-provided JSON.

and could even lead to security holes

@natario: We are talking about server-side JS here. Suppose someone is parsing user-supplied JSON. If the assumption is that the JSON is always well formed, an attacker can send some malformed JSON to trigger an error, which if spilled to the client side, may reveal vital information about the system. Or if the JSON was both malformed and contained some text with <script>..., and the error is spilled to the client side, you have an XSS bug right there. Therefore IMO it's important to handle JSON errors right where you parse it.

@Krumia: Are you talking about security holes in user-supplied JSON that was added via the require statement? I think var config = require(jsonFile); will be literally as "user-supplied" as any other source code, correct? It would be handled at source compile-time.

@NickSteele: However, I changed "this is not recommended" to "I do not recommend". I hope you are happy now.

javascript - How to parse JSON using Node.js? - Stack Overflow

javascript json node.js
Rectangle 27 236

Parsing a string containing JSON data

You can use JSON.parse()

You should be able to use the JSON object on any ECMAScript 5 compatible JavaScript implementation. And V8, upon which Node.js is built is one of them.

var str = '{ "name": "John Doe", "age": 42 }';
var obj = JSON.parse(str);

You'll have to do some file operations with fs module.

var fs = require('fs');

fs.readFile('/path/to/file.json', 'utf8', function (err, data) {
    if (err) throw err; // we'll not consider error handling for now
    var obj = JSON.parse(data);
});
var fs = require('fs');
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));
var obj = require('path/to/file.json');

But, I do not recommend this for several reasons:

  • require will read the file only once. Subsequent calls to require for the same file will return a cached copy. Not a good idea if you want to read a .json file that is continuously updated. You could use a hack. But at this point, it's easier to simply use fs.
  • If your file does not have a .json extension, require will not treat the contents of the file as JSON.
  • require is synchronous. If you have a very big JSON file, it will choke your event loop. You really need to use JSON.parse with fs.readFile.
JSON.parse

If you are reading large number of .json files, (and if you are extremely lazy), it becomes annoying to write boilerplate code every time. You can save some characters by using the jsonfile module.

var jf = require('jsonfile');
jf.readFile('/path/to/file.json', function(err, obj) {
  // obj contains JSON data
});
var obj = jf.readFileSync('/path/to/file.json');

If the JSON content is streamed over the network, you need to use a streaming JSON parser. Otherwise it will tie up your processor and choke your event loop until JSON content is fully streamed.

If you are unsure if whatever that is passed to JSON.parse() is valid JSON, make sure to enclose the call to JSON.parse() inside a try/catch block. A user provided JSON string could crash your application, and could even lead to security holes. Make sure error handling is done if you parse externally-provided JSON.

and could even lead to security holes

@natario: We are talking about server-side JS here. Suppose someone is parsing user-supplied JSON. If the assumption is that the JSON is always well formed, an attacker can send some malformed JSON to trigger an error, which if spilled to the client side, may reveal vital information about the system. Or if the JSON was both malformed and contained some text with <script>..., and the error is spilled to the client side, you have an XSS bug right there. Therefore IMO it's important to handle JSON errors right where you parse it.

@Krumia: Are you talking about security holes in user-supplied JSON that was added via the require statement? I think var config = require(jsonFile); will be literally as "user-supplied" as any other source code, correct? It would be handled at source compile-time.

@NickSteele: However, I changed "this is not recommended" to "I do not recommend". I hope you are happy now.

javascript - How to parse JSON using Node.js? - Stack Overflow

javascript json node.js
Rectangle 27 1792

Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JavaScript is based on). Its usage is simple:

For the browsers that don't you can implement it using json2.js.

As noted in the comments, if you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers.However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:

var json = '{"result":true,"count":1}',
    obj = JSON && JSON.parse(json) || $.parseJSON(json);

This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.

@Marwan: IE 8+ supports JSON.parse(). For IE 6, 7 and other older browsers, you can use the json2.js I linked to from my post. Alternatively, but less securely, you can use eval.

JSON.stringify()

Note to reviewers: please thoroughly check peer edits before allowing them, as your actions may cause unwanted side-effects for users copying and pasting code from answers.

It's not necessary to check for native support first and then fall back to jQuery. jQuery 1.10 tries JSON.parse first, then the own implementation. jQuery 2.x is directly calling JSON.parse without checking or fallback.

Parse JSON in JavaScript? - Stack Overflow

javascript json parsing
Rectangle 27 2

If you want the user be able to switch between different views, and this is data that can simply be included on page load, then just include onload then hide/show or load as json and then populate as needed.

If this is a very simple request that needs to be updated as needed and you don't plan on other similar needs in your app then just return html.

However if you are making a request that submits data or performs some action, I am a fan of returning a consistent json response with error boolean, error message and content/data elements.

jquery - Javascript - Json or html? - Stack Overflow

javascript jquery asp.net-mvc ajax json
Rectangle 27 2

To me, the coolest way of doing AJAX is returning slim data packets, not pre-rendered HTML. So I would say go with the JSON option...

... But it all depends of your needs. It is much easier to show pre-rendered HTML snippets, so if you need something fast a partial view may be a better option.

But all this has been discussed before. So take a look at this link: The AJAX response: XML, HTML, or JSON?. The author presents a good, platform independent summary of the 3 main AJAX response options, with advantages and disadvantages of each one.

jquery - Javascript - Json or html? - Stack Overflow

javascript jquery asp.net-mvc ajax json