8

I'm trying to make an autocomplete script. I pass variables through JSON, and then I don't know how to go on to decode JSON.

This is an example of the JSON code I got, and I'd like to convert it in a simple javascript array:

[{"ID":"1","name":"Amateur astronomy \r"},{"ID":"2","name":"Amateur microscopy \r"},{"ID":"173","name":"Amateur radio \r"},{"ID":"299","name":"Amateur astronomy \r"},{"ID":"349","name":"Amateur theater \r"}] 
Giulio Colleluori
  • 159
  • 1
  • 3
  • 12

2 Answers2

27

The standard JavaScript way to do this would be to use JSON.parse:

var myArray = JSON.parse(someJSONString);

For compatibility with older browsers that lack a built-in JSON object, jQuery has its own method:

var myArray = jQuery.parseJSON(someJSONString);

Such method is deprecated as of jQuery/3.0.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
icktoofay
  • 126,289
  • 21
  • 250
  • 231
17

The standard way with JavaScript is to use JSON.parse:

var myObject = JSON.parse( rawJSON );

If you're using jQuery with $.ajax (or alternative) you can use dataType: 'json'

$.ajax({ 
    type: 'GET', 
    url: 'request.php', 
    data: { variable: 'value' }, 
    dataType: 'json',
    success: function(data) { 
        // you can use data.blah, or if working with multiple rows
        // of data, then you can use $.each()
    }   
});

Although, if your server sent back the header Content-Type: application/json jQuery would return it like this anyway.

Although the other way with jQuery is using $.parseJSON(rawJSON); You don't have to do this if you're using the dataType.

var JSONArray = $.parseJSON(rawJSON);
Mark Hughes
  • 418
  • 3
  • 16
  • This is my ajax call: [link](http://pastebin.com/AMxQi1Xg) But actually doesn't work, console says that JSONArray is null :/ – Giulio Colleluori Jul 21 '13 at 11:03
  • Since you made the dataType to json you can scrap `var JSONArray = $.parseJSON( data );` as it's already converted. I edited my answer to make more sense for you. – Mark Hughes Jul 21 '13 at 12:34