Kit Kit - 1 year ago 105
Javascript Question

Retrieve plain text JSON, insert into JavaScript

I have a URL
that returns an
. 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
and assign the resulting JSON array into the
variable inside

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.


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 = ""
page = urllib2.urlopen(url)
page_source =

This time,
is already a Python
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 = ""
page = urllib2.urlopen(url)
page_source =
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
    a URL.

  2. Read the source.

  3. Interpret source as JSON.

  4. Assign it to a variable.

Answer Source

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:

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(); "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 );

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