1

for example i have this json object:

{"h":["username","hair_color","height"],"d":[["ali","brown",1.2],["mar 
c","blue",1.4],["joe","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

1
  • 1
    There's nothing about JSON in this question. Commented Aug 22, 2011 at 5:15

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
})

1 Comment

I wont be using jquery. But anyway this answer is still helpful. thanks
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.