parsing json text
for example i have this json object:
{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["mar
c","blue",1.4],["jo开发者_StackOverflow社区e","brown",1.7],["zehua","black",1.8]]}
how do i convert this into:
[{"username":"ali","hair_color":"brown","height":1.2},{"username":"mar
c","hair_color":"blue","height":1.4},{"username":"joe","hair_color":"b
rown","height":1.7},{"username":"zehua","hair_color":"black","height":
1.8}]
using javascript
There's no "special" way to do it. Assuming the first example is a JSON string, you need to first run it through JSON.parse
, and then iterate over the resulting object to generate the structure you want.
As @Jani said, parsing the JSON is the easy part. You need to do some transformations, here it is with a little help from jQuery:
var obj = JSON.parse('{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["marc","blue",1.4],["joe","brown",1.7],["zehua","black",1.8]]}')
// the array of keys (username, hair, height)
var keys = obj.h
// the array of values (arrays)
var values = obj.d
// map the values array to a new one
var users = $.map(values, function(userdata, i){
var user = {}
// assign this user's values for each key
$.each(keys, function(key_index, key){
user[key] = userdata[key_index]
})
return user
})
a = {"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["mar c","blue",1.4],["joe","brown",1.7],["zehua","black",1.8]]}
b = []
for(var i = 0; i < a.d.length; i++){
b.push({});
for (var j = 0; j < a.h.length; j++) {
b[b.length-1][a.h[j]] = a.d[i][j];
}
}
alert(b[2].username) //joe
精彩评论