Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery JSON Decode ( PHP to Javascript)

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"}] 
like image 300
Giulio Colleluori Avatar asked Jul 21 '13 00:07

Giulio Colleluori


People also ask

How to decode the JSON data in jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. As similar to the above strings, multiple other malformed strings will cause an exception.

What is parseJSON?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

What does the JSON parse () method do when we initiate an Ajax request?

Description: Takes a well-formed JSON string and returns the resulting JavaScript value.

What is JSON decode and encode?

JsonEncoder and JsonDecoder​A decoder is a function that takes a CharSequence and returns a Right with the decoded value or a Left with an error message. An encoder is a function that takes a value of type A and returns a CharSequence that represents the encoded value (JSON string).


2 Answers

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.

like image 103
icktoofay Avatar answered Oct 08 '22 22:10

icktoofay


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);
like image 35
Mark Hughes Avatar answered Oct 08 '22 22:10

Mark Hughes