JQuery JSON Decode (PHP for Javascript)

I am trying to make an autocomplete script. I pass variables through JSON, and then I do not know how to continue decoding JSON.

This is an example of the JSON code I received, and I would like to convert it to 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"}] 
+4
source share
2 answers

The standard JavaScript method for this would be to use JSON.parse :

 var myArray = JSON.parse(someJSONString); 

For compatibility with older browsers that don't have a built-in JSON object, jQuery has its own method :

 var myArray = jQuery.parseJSON(someJSONString); 

This method is deprecated as jQuery / 3.0.

+18
source

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

 var myObject = JSON.parse( rawJSON ); 

If you are using jQuery with $.ajax (or an 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 Content-Type: application/json header, jQuery would still return it like that.

Although another way to use jQuery is using $.parseJSON(rawJSON); You do not need to do this if you are using dataType.

 var JSONArray = $.parseJSON(rawJSON); 
+10
source

Source: https://habr.com/ru/post/1492525/


All Articles