Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Parsing JSON array

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.

like image 553
David Cahill Avatar asked May 05 '12 15:05

David Cahill


People also ask

How do you parse an array of JSON objects?

Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

Can a JSON file be an array?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0).

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

What is JSON parse?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.


1 Answers

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);     }); }); 
like image 56
kapa Avatar answered Sep 18 '22 21:09

kapa