29

I have a JSON output like the following:

["City1","City2","City3"]

I want to get each of the city names, how can i do this?

$.getJSON("url_with_json_here",function(json){

});

EDIT:

$.getJSON('url_here', function(data){
    $.each(data, function (index, value) {
      $('#results').append('<p>'+value+'</p>');
        console.log(value);
    });
});

The above doesn't seem to be working, no values are outputted.

Barlas Apaydin
  • 7,233
  • 11
  • 55
  • 86
David Cahill
  • 419
  • 2
  • 5
  • 9
  • Are you using `getJSON()` to fetch the JSON? Because then it should already be fetched. Hard to help without any code examples. Are you that new that you have never written any code? – kapa May 05 '12 at 15:18
  • please see my edit, i'm just confused how to retrieve the items from the url – David Cahill May 05 '12 at 15:20

5 Answers5

55

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});
Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
  • Make sure the JSON is arriving :). Try `console.log(data);`. The example you edited into your question should work. – kapa May 05 '12 at 15:37
  • @user1083813 Created a [little simulation](http://jsfiddle.net/wTCAM/1/) for you that proves your code working. – kapa May 05 '12 at 15:49
  • ok i think the problem is the url, i'm using php json_encode to output the JSON, is this sufficient for the $.getJSON method? – David Cahill May 05 '12 at 15:59
  • @user1083813 It is easy to test. Write the URL (that you would use in getJSON) in your browser and check the JSON. `json_encode()` should be sufficient, but your code might have errors or other stuff it echoes. – kapa May 05 '12 at 16:03
  • I had better luck with `$.each($.parseJSON(data), function (index, value)` using the OP's array. – secretwep Feb 16 '16 at 19:50
  • @secretwep Luck is not a factor here. `getJSON()` already parses the JSON, in fact it calls the `parseJSON()` method itself for you. – kapa Feb 16 '16 at 20:01
  • @kapa I thought it would call parseJSON too, and perhaps it does, but if I don't include `$.parseJSON()` I get a console error: `Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["City1","City2","City3"]` in jquery-2.2.0 So without factoring in luck, stochastic processes or demonic summons, something else must be amiss in my environment. – secretwep Feb 17 '16 at 19:17
  • @secretwep Hard to tell without knowing your environment, of course. I am quite confident it is not jQuery's fault. Ask an SO question, do not forget to add sufficient details. – kapa Feb 17 '16 at 21:01
  • By experience, depending on the jQuery version you're using, automatic JSON parsing might silently fail in certain situations, returning a string. Make sure you return the data with the correct `application/json` content type from your server side script. Also make sure the returned JSON string is valid: an extra comma for example might parse using one browser/function, but fail on others. – DarthJDG Feb 18 '16 at 09:09
32

Use the parseJSON method:

var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);

Then you have an array with the city names.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • great thanks, so if i'm using the above with the $.getJSON method, would this code go in the function run after successfully getting the JSON from a URL? – David Cahill May 05 '12 at 15:18
  • 1
    @user1083813: If you are fetching JSON using AJAX, then you should specify that the data type is JSON. Then it will be parsed automatically, and the success callback will get an object or array instead of a string. If you are using the `getJSON` method, the data type is set to JSON automatically, so you don't have to parse the result. – Guffa May 05 '12 at 15:33
  • This is what I needed. I already had the JSON string in session and no AJAX fetching was necessary. Thx. – zkent Oct 15 '14 at 17:57
  • This handle's the OP's array better when combined with the accepted answer. – secretwep Feb 16 '16 at 19:48
9
var dataArray = [];
var obj = jQuery.parseJSON(yourInput);

$.each(obj, function (index, value) {
    dataArray.push([value["yourID"].toString(), value["yourValue"] ]);
});

this helps me a lot :-)

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
Andrej Gaspar
  • 231
  • 2
  • 8
1
var dataArray = [];
var obj = jQuery.parseJSON(response);
  for( key in obj ) 
  dataArray.push([key.toString(), obj [key]]);
};
Mohammed Amine
  • 129
  • 1
  • 5
1

with parse.JSON

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
Miller
  • 34,962
  • 4
  • 39
  • 60
tailor
  • 366
  • 3
  • 6
  • 20