1

I'm trying to parse the following and display a simple output list showing "City, State":

{
"status":"success",
"data":[
    {"city":"Brooklyn Park","state":"MN"},
    {"city":"Campbellsport","state":"WI"},
    {"city":"Wauwatosa","state":"WI"},
            ...
    ]
}

Here's what I have so far:

var output = $.parseJSON(data);
var list = output.data;
$.each(list,function(){
    item = $.parseJSON(list);
    console.log(list.city);
});

where the original data is from a callback.

6 Answers 6

5

$.parseJSON will parse the entire object, you don't need to parse each element.

var output = $.parseJSON(data);
var list = output.data;

$.each(list,function(i,item){
    console.log(item.city);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Knew it was something stupid. I'll select your answer as soon as SO let's me...
5
var output = $.parseJSON(data);
var list = output.data;
$.each(list,function(index, val){

    // within val you'll get each 
    // data object

    console.log( val.city );
});

You not need to parse again within the $.each(). Because, output is already parsed so you can get the list using output.data.

Comments

0

data is an array so just use a for loop

var output = $.parseJSON(data);
var list = output.data;
for (var i=0; i<list.length; i++){
    var city = list[i].city;
    var state = list[i].state;
    console.log(city + "," + state);
}

Comments

0

Try this:

var output = $.parseJSON(data);
var list = output.data;

$.each(list, function() {
  console.log(this['city']); // could also be this.city
});

When you jump into any function like that inside of jQuery you then switch to "this" - the data in each "list" is not getting saved into item correctly.

Comments

0
success: function (response) {

                       var output = response[0].City;



                       alert(output);

                   }

1 Comment

I think this would help.If you want to get first city then use 0 and keep on increasing number for further cities.
0

this may help.

var json = [
    {"id":"1","tagName":"apple"},
    {"id":"2","tagName":"orange"},
    {"id":"3","tagName":"banana"},
    {"id":"4","tagName":"watermelon"},
    {"id":"5","tagName":"pineapple"}
];

$.each(json, function(idx, obj) {
    alert(obj.tagName);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.