climboid
climboid

Reputation: 6962

parsing json with jquery

So I have a json object

var json = {"School":{"Keywords":"HBS","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"}, "School":{"Keywords":"Stanford","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"}}

And I want to loop through it to find all of the keywords in this object. I've tried $(json.School).each(function(){ console.log(this.Keywords) } but it doesn't seem to work. Any clues?

Upvotes: 0

Views: 307

Answers (4)

Shawn
Shawn

Reputation: 19823

First, json is a terrible variable name. The JSON there is invalid. The first { should be a [, and the last } should be an ]. You should probably just ditch that redundant "School" property as well.

Fixing that:

var schoolArray = [
    {"Keywords":"HBS","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"},
    {"Keywords":"Stanford","SchoolName":"","SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"}];

$.each(schoolArray, function(key, value)
{
    var keywords = value.Keywords;
    var schoolName = value.SchoolName;
});

Upvotes: 0

Blender
Blender

Reputation: 298532

Your json object is a nested dictionary array. Reference its elements with strings, like this:

$.each(json['School'], function() {...

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

$.each is used with arrays. What you have is not an array. It is a simple javascript object with properties. Here's how an array would look like in javascript:

var json = [
    {
        "Keywords":"HBS",
        "SchoolName":"",
        "SchoolUrl":"/Careers/Apply/University_recruiting/Schools/HBS.aspx"
    }, 
    {
        "Keywords":"Stanford",
        "SchoolName":"",
        "SchoolUrl":"/Careers/Apply/University_recruiting/Schools/Stanford.aspx"
    }
];

Now you can loop:

$.each(json, function() {
    console.log(this.Keywords);
});

And here's a working live demo.

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

You should use for...in

for (key in json){
    if (json.hasOwnProperty(key)) {
        alert(json[key]);
    }
}

always check if the properties is of the object to avoid properties inherited from the prototype

EDIT - that is way to iterate over properties of the object, but i don't know if yours is a valid object

Upvotes: 0

Related Questions