3

Possible Duplicate:
JSON to javaScript array

Can anybody point me out how i can convert a json data to an array using java script in order to draw a chart from de data. The JSON is structured as follows:

{
"d":{
  "results":[
     {
       "_metadata":{
          "uri": "http://www.something.com/hi",
          "type" : "something.preview.hi"
          }, "Name", "Sara", "Age": 20, "Sex" : "female"
     },
       "_metadata":{
           "uri": "http://www.something.com/hi",
           "type" : "something.preview.hi"
          }, "Name", "James", "Age": 20, "Sex" : "male"
     } 
   ]
  }
}

I would like to convert this jason to the following format:

var sampleData = [
                { name: 'Sara', Age: 20, Sex: 'female'},
                { name: 'James', Age: 20, Sex: 'male'}
            ];

Does anyone have any advice on how to achieve this?

Community
  • 1
  • 1
wingman55
  • 119
  • 2
  • 2
  • 8
  • 3
    please use json instead of jason – Dhiraj May 09 '12 at 14:39
  • 2
    That's a JavaScript object literal, not JSON. – Matt Ball May 09 '12 at 14:40
  • What is the problem? You can find information how to parse JSON all over the web. Then you have to iterate over your structure and convert it in the format you want. [Working with Objects](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects) might help. – Felix Kling May 09 '12 at 14:42

2 Answers2

8
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
    var result = results[i];
    sampleData.push({ name: result.Name, Age: result.Age, Sex: result.Sex });
}
jmar777
  • 38,796
  • 11
  • 66
  • 64
1

You just have to iterate through the results array in your javascript object and build a new array that has the data in the format you want.

var results = data.d.results;
var sampleData = [], item;
for (var i = 0, len = results.length; i < len; i++) {
    item = results[i];
    sampleData.push({name: item.Name, Age: item.Age, Sex: item.Sex});
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979