I have JSON returned from my server like:
{
"user": 开发者_如何学Python{
"nickname": "Ann",
"width": 90,
"height": 60
},
"user": {
"nickname": "Dan",
"width": 60,
"height": 90
}
}
I need to iterate thru all users and for example alert thare nicknames so I try next code:
var obj = jQuery.parseJSON('{ "user": { "nickname": "ole", "width": 333, "height": 222 }, "user": { "nickname": "jak", "width": 333, "height": 222 }}');
for (user in obj ) {
alert( obj[user][nickname]);
}
Which fails. What shall I do to alert all user names (I cant change how server returns json=( so I hope to find solution on JS side.)
Code is dying alive here.
The problem you have is you have an array inside and array. You need to use something like
var obj = jQuery.parseJSON('[ {"user": { "nickname": "ole", "width": 333, "height": 222 }}, {"user": { "nickname": "jak", "width": 333, "height": 222 }}]');
for (i=0;i<obj.length;i++) {
alert(obj[i].user.nickname);
}
Each "user" is part of the array i.e. 0,1...
Also, as others have pointed out. You need to put the names in quotes.
Lastly, the JSON was wrong. As you can see it should have contained the array brackets. This code works. You can reference well formed JSON at www.json.org. Ultimately the server is going to have to give you valid JSON if you want to iterate users.
Honestly, if you want to do this reliably, you can modify an existing pure JS JSON parser. For instance, take a look at Douglas Crockford's simple recursive descent parser "parse_json": https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
At line 272 (in the object function) we have:
if (Object.hasOwnProperty.call(object, key)) {
error('Duplicate key "' + key + '"');
}
object[key] = value();
We could replace this with:
if (Object.hasOwnProperty.call(object, key)) {
if (Object.hasOwnProperty.call(dupKeys, key) && dupKeys[key]) {
object[key].push(value());
} else {
object[key] = [ object[key], value() ];
dupKeys[key] = true;
}
} else {
object[key] = value();
}
Of course, around line 259 we'd have to add the variable dupKeys,
var key,
object = {},
dupKeys = {};
And then json_parse would parse your JS.
var obj = json_parse("... your bad JSON here ...");
obj.user.forEach(function(user) {
alert(user["nickname"]);
});
Change nickname to "nickname" since you don't have a variable defined for it:
alert( obj[user]["nickname"]);
Since you can't change your JSON server-side you need to change it client-side before you parse it.
Given the JSON mentioned you could use this function:
function fixData( d ) {
d = d.replace(/,\s*\"user\"\:/, ",");
d = d.replace(/\"user\"\:/, "\"users\":[");
d = d.replace(/}\s*$/, "]}");
return d;
}
And simply "fix" the JSON before running parseJSON
via:
var obj = jQuery.parseJSON(fixData(/* JSON string */));
Fiddle with my solve
If you would like to then loop through each user and output "nickname":
jQuery.each(obj.users, function(){ alert(this.nickname); });
Please note: Obviously the regex in the the fixData
function is fragile and shouldn't be used as a general solve for any other data sources; you would need to rewrite it to your specific use case if it doesn't match exactly.
There are two issues.
First, keys must be unique. You're using the key user
twice in the same object notation. You'd be better to use array notation.
Second, [nickname]
should be .nickname
or ["nickname"]
.
var json = '{ "user": { "nickname": "ole", "width": 333, "height": 222 }, "user": { "nickname": "jak", "width": 333, "height": 222 }}';
// make it an Array
json = '[' + json.slice(1,-1).replace(/"user":/g,'') + ']';
var obj = $.parseJSON( json );
for (var i = 0, len = obj.length; i < len; i++ ) {
alert( obj[i].nickname);
}
Example: http://jsfiddle.net/z7YxR/
精彩评论