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?

3
  • 3
    please use json instead of jason Commented May 9, 2012 at 14:39
  • 2
    That's a JavaScript object literal, not JSON. Commented May 9, 2012 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 might help. Commented May 9, 2012 at 14:42

2 Answers 2

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.