Best way to JSON parsing using JavaScript
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?
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
Please validate your json string in some websites http://jsonformatter.curiousconcept.com/
Since javascript is a script language, it will interpret the script and terminate the interpretation at the moment when it has some syntax errors. Try to use some javascript console in your browser
IE - Developer Tools
Firefox - firebug plugin
Let's assume that the actual object you have is valid (no missing commas etc), and you've parsed the string correctly, you're trying to access objects with array indexes and vice versa. Let's rebuild the object from ground up:
First, you have an array.
[]
You access the first element in the array using data[0]
. The first element is an object.
[
{}
]
The object has two keys, which both hold objects.
[
{
"student": {},
"user": {}
}
]
You access the student
key with data[0].student
. It contains and object with two keys.
[
{
"student": {
"name": "ABCD",
"age": 8
},
"user": {}
}
]
You get the number of values in that object with:
Object.keys( data[0].student ).length;
For better browser support see Length of a JavaScript object
链接地址: http://www.djcxy.com/p/27264.html上一篇: 从多维数组获取数组长度