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"}]
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.
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.
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
JsonEncoder and JsonDecoderA 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).
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With