9

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"}] 
2
  • what to do if i have special character in json string?? Commented Sep 18, 2014 at 10:13
  • I know it's been over 2 years, but did you ever figure out how to do this? Commented Oct 13, 2015 at 21:04

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

19

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

2 Comments

This is my ajax call: link But actually doesn't work, console says that JSONArray is null :/
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.