In this post, we will lean parse json in ajax. This article will give you a easy example of how to parse json in jquery ajax response. This post will give you a easy example of jquery parse json array.
This parseJSON() method in jquery takes a well-formed JSON string and returns the javascript value.
jQuery.parseJSON() was a utility function provided by the jQuery library.
Syntax:
jQuery.parseJSON(json)
Parameters: The parseXML() method access only one parameter that is mentioned below.
- json: This parameter is the well-formed JSON string to be parsed.
Example 1:
<script>
let text = '{"id": 1, color":"red", "type": 1}'
let object = jQuery.parseJSON(text);
console.log(object);
</script>
Example 2: How to parse json in jquery ajax using JSON.parse() method
JSON.parse() is a built-in Javascript function that convert a JSON string into a Javascript object. To parse JSON data in JQuery ajax, you can use the JSON.parse() to convert JSON string to a javascript object easily. Let’see below example.
$.ajax({
url: 'test.php',
dataType: 'json',
success: function(data) {
/* Parse the JSON data */
var objectData = JSON.parse(data);
/* Access the object properties */
console.log(objectData.property1);
console.log(objectData.property2);
}
});
In this example, we are making an AJAX request to the test.php URL and specify dataType as JSON. This request jQuery to parse the response as JSON data.
In the seccess callback function we can access JSON data as a Javascript object by calling JSON.parse() on the data parameter. We can then access the object properties by using dot notation.
Note JSON.parse() method will throw a syntax error. You can use a try-catch block to handle this error and display a helpful message to the artisan.
I hope this tutorial help you.