0

How to convert JSON string with key-value pair into string with only values in javascript.

For example my JSON output looks like this

{
  "data": {
    "BearCollection": {
      "BearDetails": [
        {
          "Name": "James",
          "x": "81.43410000",
          "y": "6.32813300"
        },
        {
          "Name": "James",
          "x": "81.43489000",
          "y": "6.32763300"
        },
        {
          "Name": "Sera",
          "x": "81.4377000",
          "y": "6.32453300"
        }
      ]
    }
  },
  "xhr": {}
}

I want to convert it using javascript as

var details=[
  [
    "James",
    81.4341,
    6.328133
  ],
  [
    "James",
    81.43489,
    6.327633
  ],
  [
    "Sera",
    81.4377,
    6.324533
  ]
];

Is there any way to do this?

1
  • Use JSON.parse(); and iterate through the json objects and build the required data. Commented Mar 28, 2014 at 9:41

3 Answers 3

1
var json = "Your JSON string";
obj = JSON.parse(json);

for(int i= 0; i< obj.data.BearCollection.BearDetails.length;i++)
{
   String Name = obj.data.BearCollection.BearDetails[i].Name;
   String x = obj.data.BearCollection.BearDetails[i].x;
   String y = obj.data.BearCollection.BearDetails[i].y;

  ..fill Array (pseudo - do some work yourself ;) )
}
Sign up to request clarification or add additional context in comments.

4 Comments

the question asked for JavaScript?
@Bergi and the code above is? (Except for som pseudo)
StackOverflow is in my eyes help to help yourself. Not to get complete solutions. But that's my opinion.
Nothing wrong with that, but you might should have stated that. Especially the type annotations confused me, and …fill Array should be marked as a comment
0

Use JSON.parse to get the object from the JSON string, then access the BearDetails, convert each element to an array, and stringify the new collection again:

var obj = JSON.parse(jsonstring);
var details = obj.data.BearCollection.BearDetails.map(function(detail) {
    return [detail.Name, detail.x, detail.y];
});
return JSON.stringify(details);

Comments

0
$(document).ready(function() {
var data = JSON.parse('{"data": {"BearCollection": {"BearDetails": [{"Name": "James","x": "81.43410000","y": "6.32813300"},{"Name": "James","x": "81.43489000","y": "6.32763300"},{"Name": "Sera","x": "81.4377000","y": "6.32453300"}]}},"xhr": {}}');

var bear;
var arr = [];
var nestedArr;
for (i in data.data.BearCollection.BearDetails) {
    bear = data.data.BearCollection.BearDetails[i];

    nestedArr = [];
    nestedArr.push(bear.Name);
    nestedArr.push(bear.x);
    nestedArr.push(bear.y);

    arr.push(nestedArr);
}

});

1 Comment

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.