简体   繁体   中英

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 the hardcoded string so that I can use $.each(test, function(a,b){}))

Thank you for your time.

Original Question:

jQuery makes a point of not including a publicly accessible JSON parser or encoder. They want you to use a 3rd party library for that.

I recommend the one hosted at json.org:

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

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

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


In answer to "why doesn't jQuery make it's parser available?":

jQuery doesn't actually include a parser of any sort. In the AJAX section of jQuery's codebase, you can actually see what they do on lines 572-579 .

The quick version is that they actually do a check to see if you've included an external JSON library such as the one from json.org, and if it finds it, they use that to parse. If you have not included one, they return the json wrapped in a function, effectively returning it for evaluation. Very tricky, but very smart!

Do you people realize, that JSON means "JavaScript Object Notation"? If you have JavaScript Object Notation hardcoded, then just loose the quotes and you're done with parsing it as JavaScript parser will take care of that.

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

Easy, wasn't it?!! There might be something I'm not aware of, but for me it is quite difficult to understand people writing parsers in JavaScript for JavaScript... Sure if you're not sure about the security of source your jsonstr comes from, then evaluating it straight out of the box might not be the best idea, but in case you and only you control the source and especially if you're hardcoding it like it was said in the question, then just loose the quotes!

以下是当数据类型设置为“json”时jQuery在ajax请求中执行的操作(这是getJSON所做的,在引擎盖下):

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

Unfortunately jQuery doesn't support JSON parsing outside of the AJAX functions with JSON or JSONP as datatype (deserialization si very tightly bound to the AJAX and Callback code). You can of course just do a

var obj = eval(test);

But this is definitely not the recommened way (except for when you know for sure that your string is only a JavaScript object and not arbitrary source code to be executed). So the best way is probably to use another library like the JSON2 library (found on json.org ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM