Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...