0

I have JSON data that looks like this:

[{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}]

I need it to look like this instead:

[{"age": 31},
{"height (inches)": 62},
{"location": "Boston, MA"},
{"gender": "male"}]

This is for a jQuery web app. How would I go about this conversion? Not picky about how it gets done, just having trouble finding an existing solution. Thanks!

tylerl
  • 1,160
  • 1
  • 19
  • 41
  • How you wan to implement? Some code plz just don't throw problem. – αƞjiβ Apr 28 '15 at 18:03
  • I don't care if it's a function, a loop, or a one-liner. I'm sorry, I should've stated that I'm just using JS w/ jQuery. – tylerl Apr 28 '15 at 18:08
  • Parse the JSON, use `.map` to convert each element and stringify the result back to JSON. – Felix Kling Apr 28 '15 at 18:09
  • 3
    It looks like you are `serializeArray` to get the data (which btw returns an array of objects, not JSON). In that case you might want to have a look at [Convert form data to JavaScript object with jQuery](http://stackoverflow.com/q/1184624/218196) – Felix Kling Apr 28 '15 at 18:14
  • why don't you put them all in one object? it would be a lot easier to work with later, unless you're expecting duplicate keys... – dandavis Apr 28 '15 at 18:48

3 Answers3

2

This should do the trick:

a = [{"name":"age","value":31},
     {"name":"height (inches)","value":62},
     {"name":"location","value":"Boston, MA"},
     {"name":"gender","value":"male"}];

b = a.map(function(item){
  var res = {}; 
  res[item.name] = item.value; 
  return res;
});

console.log(b);
Cristik
  • 30,989
  • 25
  • 91
  • 127
0

var jsonData = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];

var newObj = [];
jsonData.forEach(function(d){
    var obj = {};
    obj[d.name] = d.value;
    newObj.push(obj)
});
console.log(JSON.stringify(newObj))
Yellen
  • 1,785
  • 16
  • 35
-1

Parse your JSON string, then iterate and build a string as show here:

var s = [{"name":"age","value":31},{"name":"height(inches)","value":62},{"name":"location","value":"Boston, MA"},{"name":"gender","value":"male"}];

var h='[';
for(var i = 0; i<s.length; i++){
  h+='{"'+s[i].name+'":"' + s[i].value + '"}'
  if(i!=s.length-1){
    h+=','
  }
}
h+=']';
h=JSON.parse(h);
em_
  • 2,134
  • 2
  • 24
  • 39