-4

i am trying to convert json array

                {"id":"1","name":"abc"},
                {"id":"2","name":"pqr"},
                {"id":"3","name":"xyz"};

into this kind of js array

 var locations = [
    [1, 'abc'],
    [2, 'pqr'],
    [3, 'xyz']
];
4
  • 3
    And what have you tried so far? Commented Mar 12, 2014 at 11:23
  • 3
    As written, that's not a JSON array--I assume that's a typo. Which part is causing you a problem? Commented Mar 12, 2014 at 11:23
  • by using this location array i am trying to create multiple markers on google map Commented Mar 12, 2014 at 11:26
  • What you are calling a "json array" is neither JSON nor an array. Is that text in a string? Is it the (text) response from an Ajax call? Is it perhaps supposed to be a JS array of objects? Or...? Commented Mar 12, 2014 at 11:31

2 Answers 2

1

I'm assuming you have the elements objects, (and not as Json as you state):

var data = [{"id":"1","name":"abc"},
            {"id":"2","name":"pqr"},
            {"id":"3","name":"xyz"}];

You can the convert it to a two-dimensional array like this

var output = new Array();
for (var i = 0; i < data.length; i++) {
    output[i] = new Array(data[i].id, data[i].name);
}
2
  • Actually i get this json array by using this var javaArray = <?php echo json_encode($result['result']) ?>; Commented Mar 12, 2014 at 11:33
  • in any case, try the code posted. - just add "var data=" in front of the code generated by PHP Commented Mar 12, 2014 at 11:34
0

You can do this like this.

var jsondata=[{"id":"1","name":"abc"},
                {"id":"2","name":"pqr"},
                {"id":"3","name":"xyz"}];
var arrayObj=$.parseJSON(jsondata);
2
  • 1
    Your jsondata variable is not a string, so won't work with $.parseJSON(). Commented Mar 12, 2014 at 11:30
  • i got the solution thanks to all var locations = new Array(); for (var i = 0; i < length; i++) { locations[i] = new Array(javaArray[i].id,javaArray[i].name); } Commented Mar 12, 2014 at 12:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.