Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to JSON parsing using JavaScript [duplicate]

Possible Duplicate: Length of a JavaScript object (that is, associative array)

I have JSON in the following format

[{"student":{"name" : "ABCD",
        "age":8,
        }
    "user":{ "firstName":"ABCD",
            "age": 9,
        }
        },
   {"student":{"name" : "XCYS",
        "age":10,
        }
    "user":{ "firstName":"GGG",
            "age": 11,
        }
},]

I tried using (data.student[i].length), which did not work (just to see what the length of the object is), and I also tried (data.user[i]) to no avail.

I am basically very confused on how I can get the length of one of the objects in the JSON and how I can effectively display it. How can I do this?

like image 993
alex Avatar asked Oct 08 '22 00:10

alex


1 Answers

The content in your questions doesn't parse as valid JSON as all keys need to be wrapped in quotes (so you should have "age": 11 instead of age: 11). All key/value pairs in an object should be separated by a comma (so you should have "firstName": "GGG", "age": 11 instead of "firstName": "GGG" "age": 11. You also have a trailing comma in the outer array.

So long as you have valid JSON, you should be able to use JSON.parse(data) in all browsers newer than IE7 to convert the string into an actual object. Once parsed into an object, you can use:

var data = "your JSON string";
var object = JSON.parse(data);

console.log(object.length); // the number of objects in the array
console.log(object[0].student.name; // the name of the first student

If you are supporting browsers IE7 and older, check out Douglas Crockford's JSON polyfill: https://github.com/douglascrockford/JSON-js

like image 178
steveukx Avatar answered Oct 13 '22 12:10

steveukx