jQuery JSON Decode ( PHP to Javascript)
Solution 1
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.
Solution 2
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);
Giulio Colleluori
Updated on June 22, 2020Comments
-
Giulio Colleluori almost 4 years
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 almost 11 yearsThis is my ajax call: link But actually doesn't work, console says that JSONArray is null :/
-
Mark Hughes almost 11 yearsSince 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.