Kit Kit - 5 months ago 26
Javascript Question

Retrieve plain text JSON, insert into JavaScript

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:


  1. JavaScript will
    GET
    a URL.

  2. Read the source.

  3. Interpret source as JSON.

  4. Assign it to a variable.


Answer

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-js

Use json2.js from 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:

var jsonObject = {}; 
var xhr = new XMLHttpRequest();
xhr.open( "GET", url, true );      // true makes this call asynchronous
xhr.onreadystatechange = function () {    // need eventhandler since our call is async
     if ( xhr.readyState == 4 && xhr.status == 200 ) {  // check for success
        jsonObject = JSON.parse( xhr.responseText );
     }
};
xhr.send(null);

Also, I would suggest reading this article for cross browser issues and implementation of XMLHttpRequest object.

Comments