2

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.
Kit
  • 30,365
  • 39
  • 105
  • 149
  • first of all the json you show in your example is not json. its an array of arrays. – naveen Aug 14 '11 at 06:39
  • copy [[key, value], [key, value], [key, value], ...] to http://jsonlint.com/ and check validity. please paste your actual response. – naveen Aug 14 '11 at 06:45
  • 1
    @naveen. Yes, my example per se is invalid JSON. `key` and `value` are meant to be placeholders. JSONLint didn't say anything about array of arrays being an error. It only complained about expected data types. `[["key", "value"], ["key", "value"]]` are good enough. – Kit Aug 14 '11 at 06:50
  • i stand corrected. i have always thought they would be wrappoed to a parent object – naveen Aug 14 '11 at 07:02

4 Answers4

7

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.

Robin Goupil
  • 154
  • 1
  • 3
  • 14
Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • That article is ancient. Also http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil says it's not _that_ evil ;-) – andyb Aug 14 '11 at 06:28
  • How do I retrieve `'json data'` given only the URL in the first place? I have updated my question to address it :) – Kit Aug 14 '11 at 06:31
  • @andyb: its evil and atleast john resig thinks so :). he use `new Function("return " + data)` instead of eval in `$.parseJSON`. http://james.padolsey.com/jquery/#v=1.6.2&fn=jQuery.parseJSON – naveen Aug 14 '11 at 06:34
  • @naveen I'll throw [Crockford](http://javascript.crockford.com/code.html) back at you :-) `eval has aliases. Do not use the Function constructor`. I guess my point was that _evil_ is misleading IMHO and I think _avoided unless absolutely necessary_ is a better phrase. – andyb Aug 14 '11 at 06:48
  • @andyb: good one. but it succeeds *The eval function is the most misused feature of JavaScript. Avoid it.* i guess Function constructor is the better evil for browsers without JSON. personally I use json2.js :) BTW, why should we spend quality time on discussing IE :P – naveen Aug 14 '11 at 06:59
  • You guys enhanced my post with this valuable discussion (and those good links)! Thanks! – Mrchief Aug 14 '11 at 07:07
  • @Kit: Added an example in my answer to retrieve JSON data from a URL. – Mrchief Aug 14 '11 at 07:18
0

Using JQuery is almost a standard nowadays:

$.get('/get_data', function (data) {
   //success callback

}, 'json');

I did a fiddle here, look the sample here: http://jsfiddle.net/b24GZ/ - Fetching json data from: http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo

References:

http://api.jquery.com/jQuery.get/

http://api.jquery.com/jQuery.post/

http://api.jquery.com/jQuery.parseJSON/

armandomiani
  • 732
  • 6
  • 16
  • 2
    I wouldn't say standard. There are plenty of people who use frameworks besides jQuery. I personally prefer Ender or MooTools. – beatgammit Aug 14 '11 at 07:02
0

There's a couple ways. If you're using a library of some kind, most of them have built-in JSON.parse() methods. Newer browsers (i.e. Chrome, Firefox, Safari, etc) have that capability built in.

Another way of doing it is with a jsonp callback. With this method, you define a function on your in your script and then write a script tag into the page loading the url you wish to load as its source. You pass the name of your function as a parameter to your remote uri, and your server wraps the json response with the callback. When it loads onto into the page, your function executes using the data it wraps as a javascript object.

This is a simple example:

var your_callback = function(obj){
    console.log(obj);
}

<script src="http://myapp.com/get_data/?callback=your_callback"></script>

At this point, your_callback gets executed and the "obj" variable contains your data.

Again, if you have the advantage of using a javascript library, this functionality might already be baked in. jQuery makes this bit really easy.

JSONP is typically used for cross-domain data transfer, but it works just as well locally. If you are doing this locally though, you shouldn't need to use JSONP and can use XHR requests instead.

Geuis
  • 41,122
  • 56
  • 157
  • 219
0

If you use jQuery library, it's possible to use jquery-jsonp library code.google.com jquery-jsonp

function getProfile(userId) {

$.jsonp({
  "url": "http://gdata.youtube.com/feeds/api/users/"+userId+"?callback=?",
  "data": {
      "alt": "json-in-script"
  },
  "success": function(userProfile) {
      // userProfile - is JSON data with which you can work
      // handle user profile here 
  },
  "error": function(d,msg) {
      alert("Could not find user "+userId);
  }
}); }

Also in your "http://myapp.com/get_data" page youw will need to put JSON data into callback data

callback(json_data_here)
m0rg0t
  • 132
  • 2
  • 11