I have a URL http://myapp.com/get_data that returns an application/json Content-Type. When I browse to that URL, I’d get a plain-text JSON array in my browser window
[[key, value],
[key, value],
[key, value],
...]
I also have a JavaScript function that expects data to be in JSON array format
function process_data() {
var data = // give me more data in JSON array format...
}
How do I make my JavaScript browse to http://myapp.com/get_data and assign the resulting JSON array into the data variable inside process_data()?
I’m new to JavaScript (coming from a Python background) and I would appreciate if you can suggest solutions that use the core JavaScript library. Solutions using other libraries are welcome also, preferably those that are considered best-practice.
UPDATE
It appears I wasn’t clear on my question. Let me provide an example from Python. After doing the necessary imports, I can do something like
url = "http://myapp.com/get_data"
page = urllib2.urlopen(url)
page_source = page.read()
This time, page_source is already a Python str object that I can easily play with, assign to other variables, etc. If I could mix Python and JavaScript together, for the context of this question, I want to do something like
function process_data() {
url = "http://myapp.com/get_data"
page = urllib2.urlopen(url)
page_source = page.read()
var data = convert_str_to_JSON(page_source)
}
Of course that was just an ugly mishmash of a code, but I hope it conveys what I’m trying to get at:
- JavaScript will
GETa URL. - Read the source.
- Interpret source as JSON.
- Assign it to a variable.
Newer browser support JSON parsing natively.
You can say
JSON.parse('json data'). For older browsers (such as IE 7 or 6), you can use this library: https://github.com/douglascrockford/JSON-jsUse
json2.jsfrom above library. It checks if native browser implementation is present, if not, adds it.Do not use
eval(as eval is evil)!Update: To get the ‘json data’, use this:
Also, I would suggest reading this article for cross browser issues and implementation of
XMLHttpRequestobject.