Parse JSON String

I have a hard-coded JSON string.

var test = "JSON STRING HERE"; 

I am using jQuery. I know there is a function like getJSON, but that makes an AJAX call. I want it to parse a hard-coded string so that I can use $.each(test, function(a,b){}))

Thank you for your time.

+3
source share
4 answers

The original question:

jQuery makes it a point not to include a public JSON parser or encoder. They want you to use a third-party library for this.

I recommend the one hosted on json.org:

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

Alternatively, you can use the jQuery-JSON plugin hosted on Google Code:

http://code.google.com/p/jquery-json/


In response to the question "why does jQuery not make it a parser available?":

jQuery does not actually contain a parser of any type. In the AJAX section of the jQuery code base, you can see what they do on lines 572-579 .

The quick version is that they actually do a check if you include an external JSON library, such as the json.org library, and if it finds it, they use it for analysis. If you did not enable it, they return json wrapped in the function, effectively returning it for evaluation. Very sophisticated but very smart!

+11
source

Do you understand that JSON means "JavaScript Object Name"? If you have JavaScript Object Notation hardcoded, then just lose the quotation marks and you'll end up with parsing, as the JavaScript parser will take care of that.

 var jsonstr = "{prop1: 'val1', prop2: 'val2'}"; var parsed = {prop1: 'val1', prop2: 'val2'}; 

Easy, right? !! Maybe I don’t know something, but it’s quite difficult for me to understand how people write parsers in JavaScript for JavaScript ... Of course, if you are not sure about the safety of the source jsonstr comes from, then its evaluation right out of the box, maybe , not the best idea, but if you and only you control the source, and especially if you hard-code it, as was said in the question, then just lose the quote!

+5
source

Here, what jQuery does in an ajax request when the data type is "json" (which does getJSON, under the hood):

 window["eval"]("(" + data + ")"); 
+1
source

Unfortunately, jQuery does not support JSON analysis outside of AJAX functions with JSON or JSONP as the data type (deserialization is very closely related to AJAX and Callback code). You can of course do

 var obj = eval(test); 

But this is definitely not recommended (unless you know for sure that your string is just a JavaScript object, not arbitrary source code to execute). Therefore, it is best to use another library, such as the JSON2 library (found on json.org ).

0
source

Source: https://habr.com/ru/post/1398910/


All Articles