6


can someone tell me the fastest way to parse a json string to an object without jquery? I want to parse the json string in a script tag before jquery is loaded.

Thanks in advance!
Peter

4 Answers 4

8

Use JSON JS

Sign up to request clarification or add additional context in comments.

1 Comment

This is not a native library in older browsers. You will need to include the library explicitly to cater for them.
5

To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

6 Comments

This can be dangerous as it will execute arbitrary JS. If your JSON is generated from user submitted content, you could open yourself up to XSS attacks.
Yes, of course, you should not do anything like this without proper verifications...
OP asked for fastest, as far as we know the OP controls the content behind the script tag. Good comment though.
In fact, there's nothing that can really protect you if you include a script tag to an evil server.
@Alex Ackerman the very next paragraph from json.org/js.html after the one you quoted specifically recommends against using eval.
|
2
var myObject = eval('(' + myJSONtext + ')');

1 Comment

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script...
1

If the JSON string comes from the server you can try the JSONP technique. The JSON is parsed natively in the browser(fast) when loaded and without any library.

eg: if you response is {"name":"Peter"}

A JSONP response will be something like:yourFunction({"name":"Peter"})

yourFunction must be a globally defined function in the page that will receive the call, like:

function yourFunction(json){
  //do something with the JSON
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.