Parse JSON in jQuery

JSON (JavaScript Object Notation) is a lightweight data-interchange format to parse and generate.
If you’re working with JSON data in jQuery, you can parse the data into a JavaScript object using the $.parseJSON() method.

In this article, we’ll take a look at how to use this method to parse JSON data in jQuery.

Parsing JSON in jQuery using parseJSON()

jQuery allows parsing JSON using parseJSON() method.

The parseJSON() method in jQuery internally uses the Javascript parse() method.


parseJSON() example


  $(document).ready(function() {
   var jsonStr = '{"sitename":"TopJavaTutorial","url":""}';
   var siteDetails = $.parseJSON(jsonStr);
   document.getElementById("name").innerHTML = siteDetails.sitename;
   document.getElementById("address").innerHTML = siteDetails.url;
    <h2>jQuery parseJSON() example</h2>

    <p id="name">Site name here</p>

    <p id="address">Site address here</p>



jQuery parseJson example

Edit in fiddle here


In this example, the JSON data is stored in a string, jsonString. The $.parseJSON() method is used to parse the string and convert it into a JavaScript object. Once the JSON data has been parsed, you can access its properties just like any other object.

Handling errors:

It’s important to note that the $.parseJSON() method only works with valid JSON data. If the data is not valid JSON, the method will throw an error. To avoid this, you should always validate your JSON data before trying to parse it.

var jsonString = '{"name": "John Doe", "age": 35';  // Invalid JSON

try {
  var obj = $.parseJSON(jsonString);
} catch (e) {
  console.error(e);  // Output: "SyntaxError: Unexpected end of JSON input"

© 2016 – 2023, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags