The Wayback Machine - https://web.archive.org/web/20241118222336/https://www.geeksforgeeks.org/how-to-universally-parse-json-into-blocks-using-jquery/
Open In App

How to universally parse JSON into blocks using jQuery ?

Last Updated : 18 Nov, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In jQuery, to parse any data to any block is carried over by using DOM Insertion methods. Some of DOM Insertion methods are append(), appendTo(), html(), prepend(), prependTo(), text(). To parse JSON into any block is also handled in same way but along with Ajax callback functions and parse.JSON() methods. Here parse.JSON() methods is deprecated in jQuery 3.0, so JSON.parse() method used instead in later versions.

Syntax:

/* JSON data might be in array also */
var $json-data= '{json-index:json-values}'

/* Creating object for parsed JSON data */
var $json-object= JSON.parse($jsondata);

/* Parse text along with JSON data-value
 with respect to index */
$("selected block").text($json-object.index);

or

/* Parse HTML tag along with JSON data-value
 with respect to index */
$("selected block").html( "opentag" + $json-object.index + "closetag");

Approach 1:

  • Let us apply AJAX Callback function using $.ajax() method.
  • $.ajax() method carried out in different way, but here we just passing configuration object/object literal as its sole arguments to the $.ajax() method along with JSON Array data.

Example 1: In below example, AJAX Callback function used to parse JSON array into HTML block.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
      
    <meta name="viewport"
        content="width=device-width, 
                initial-scale=1">
    <script src="
    </script>
</head>
  
<body>
    <center>
        <h1 style="color:green;">GeeksforGeeeks</h1>
        <h3>Top 3 Students List</h3>
        <br>
        <table style="border:10px;border-style: double;" 
                border="2" cellpadding="20"
                cellspacing="20">
            <thead>
                <tr>
                    <th>NAME</th>
                    <th>ROLL NO</th>
                    <th>TOTAL MARK</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td align="center"
                        data-stud="student1"
                        data-topstud="Name">
                </td>
                    <td align="center"
                        data-stud="student1"
                        data-topstud="Roll">
                </td>
                    <td align="center"
                        data-stud="student1"
                        data-topstud="TotalMark">
                </td>
                </tr>
                <tr>
                    <td align="center"
                        data-stud="student2"
                        data-topstud="Name">
                </td>
                    <td align="center"
                        data-stud="student2"
                        data-topstud="Roll">
                </td>
                    <td align="center"
                        data-stud="student2"
                        data-topstud="TotalMark">
                </td>
                </tr>
                <tr>
                    <td align="center"
                        data-stud="student3"
                        data-topstud="Name">
                </td>
                    <td align="center"
                        data-stud="student3"
                        data-topstud="Roll">
                </td>
                    <td align="center"
                        data-stud="student3"
                        data-topstud="TotalMark">
                </td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <th>:</th>
                    <th> Top 3 Students List</th>
                    <th>:</th>
                </tr>
            </tfoot>
        </table>
    </center>
  
    <script>
        var data = {
                "student1": [{
                    "Name": "Arun",
                    "Roll": 10056,
                    "TotalMark": 98,
                }],
                "student2": [{
                    "Name": "Vinoth",
                    "Roll": 10057,
                    "TotalMark": 96,
                }],
                "student3": [{
                    "Name": "Zafar",
                    "Roll": 10068,
                    "TotalMark": 85,
                }]
            }
              
        //AJAX callback:
        $('td').html(function() {
            var $block = $(this)
            return data[$block.data('stud')]
                    [0][$block.data('topstud')];
        });
          
        $("th").css("background-color", "#08f");
        $("tr:nth-child(1)").css("background-color", "green");
        $("tr:nth-child(2)").css("background-color", "yellow");
        $("tr:nth-child(3)").css("background-color", "red");
    </script>
</body>
  
</html>


Output:

Approach 2:

  • Parsing JSON string using native JSON.parse method.
  • JSON.parse method is used instead of jQuery 3.0’s deprecated method $.parseJSON().

Example 2: In below example, jQuery.parseJSON() method and JSON.parse() method used to parse JSON data into a HTML block.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="width=device-width, 
                initial-scale=1">
    <script src="
    </script>
      
    <style>
        div {
            border: 2px solid green;
            padding: 20px;
        }
          
        h2 {
            color: red;
        }
          
        b {
            color: #08f;
        }
    </style>
</head>
  
<body>
    <center>
        <h1 style="color:green;">
            GeeksforGeeeks
        </h1>
        <br>
  
        <div>
            <h2>Employee Details</h2>
            <p></p>
            <h2>Website Details</h2>
            <em></em>
        </div>
    </center>
  
    <script>
      
        // Using jQuery.parseJSON()
        var company = jQuery.parseJSON(
            '{"employee_name":"Adam","age":25,"salary":"11,500"}');
      
        $('p').html("<b>Employee Name:</b> " + company.employee_name
                    + ",<br><b>Age:</b> " + company.age + 
                    ",<br> <b>Sal/Month:</b> " + company.salary);
    </script>
      
    <script>
        $(document).text(function() {
            var $mytxt = '{ "website":"GeeksforGeeeks", 
            "url":"https://www.geeksforgeeks.org/" }'
              
            // Using JSON.parse()
            var $web = JSON.parse($mytxt);
            var $block = $('em');
            return $block.text("WebsiteName: " + 
                            $web.website +
                            ", URL: " + $web.url);
        });
    </script>
</body>
  
</html>


Output:

Reference: https://api.jquery.com/



Similar Reads

How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to parse JSON Data into React Table Component ?
In React parsing JSON Data into React Table Component is a common task to represent and structure data. We can render the JSON data into a table dynamically using the array map. Prerequisites:NPM & Node JSReact JSJSON parse()ApproachTo render JSON data in React Table we will be using the JavaScript array map method. Using the map function we wi
2 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configuration files, or databases. In this article, we wi
2 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
Moment.js Parse ASP.NET JSON Date
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. We can use the moment() function passed with a string to parse dates in ASP.NET JSON format. The moment() function is used to create a moment using a string representing a date in ASP.NET JSON format. Syntax: moment( String ) Parameters: It takes a st
1 min read
How does the JSON.parse() method works in JavaScript ?
The JSON.parse() method in JavaScript is used to parse a JSON (JavaScript Object Notation) string and convert it into a JavaScript object. JSON is a lightweight data-interchange format that is easy for humans to read and write, and it is also easy for machines to parse and generate. Example: Here, JSON.parse() take a JSON-formatted string (jsonStri
1 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However, parsing JSON data can sometimes lead to errors, e
1 min read
How to Parse JSON in JavaScript ?
Parse JSON in JavaScript, accepting a JSON string as input and returning a corresponding JavaScript object with two methods, using JSON.parse() for parsing JSON strings directly and employing the fetch API to parse JSON responses from web APIs. These techniques are crucial for seamless data manipulation and retrieval in your JavaScript projects. Be
2 min read
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a parameter to it. Syntax:JSON.parse(parsingString);We can
4 min read
How to Parse JSON Data in JavaScript ?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate it. In JavaScript, parsing JSON data is a common task when dealing with APIs or exchanging data between the client and server. Table of Content Using JSON.parse() MethodUsing eval() Func
4 min read
How to parse a JSON File in PHP?
We will explore how to parse a JSON file and display its data using PHP. PHP is a server-side scripting language commonly used to process and manipulate data. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for both humans and machines to read and write. It stores data as name/value pairs. JSON Syntax Overvie
3 min read
Split a Sentence into Fixed-Length Blocks without Breaking Words in JavaScript
Given a sentence, our task is to split it into blocks of a fixed length without breaking words using JavaScript. Example: Input: Sentence= "This is a sample sentence to demonstrate splitting into blocks without breaking words.", blocksize = 15Output:Blocks: [ 'This is a', 'sample sentence ', 'to demonstrate', 'splitting into', 'blocks without', 'br
3 min read
How to parse a URL into hostname and path in javascript ?
We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL. Example 1:This example parses the URL of the current web page. C/C++ Code <body style="
1 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
Displaying inline and multiline blocks of code using Bootstrap
Bootstrap provides a number of classes for displaying inline and multiline blocks of code. Displaying Inline Code: Inline code should be wrapped in <code> tags. The resulting text will be displayed in a fixed-width font and given a red font color. Note: The < and > tags should be replaced with &lt; and &gt; respectively. Below i
3 min read
How to Place Text Blocks Over an Image using CSS?
Placing text blocks over an image is a common technique used in web design to create visually appealing layouts. Here, we will explore different approaches to achieve this effect using CSS. Below are the approaches to place text blocks over an image using CSS: Table of Content Using Absolute PositioningUsing CSS background-imageUsing Absolute Posit
2 min read
How to parse URL using JavaScript ?
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example: URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use
2 min read
How to parse and process HTML/XML using PHP ?
In this article, we will learn how to process XML using PHP. We have already learnt the basics of XML and their differences with respect to HTML. Different elements of XML can be learnt from XML Elements to understand the working of the following programs. The simplexml_load_string() function is used to parse the given XML and then the XML object c
2 min read
How to Parse and Compile Expressions Using math.js?
Parsing and compiling in math.js consists of converting mathematical expressions into a structured format and preparing them for evaluation. This involves parsing the expression to create an abstract syntax tree, compiling this tree into a more efficient form, and then evaluating it with specific variable values.\ Table of Content Basic Parsing and
3 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code <h1 st
2 min read
Convert JSON file into CSV file and displaying the data using Node.js
There are so many ways to store data for better understanding for individual purposes, in few cases, JSON files will be more suitable in few cases, CSV files, and there are also lots of other types as well like XML, etc. In this article, we will convert the JSON file data into CSV file data and also display that through Node.js. JSON stands for Jav
3 min read
How to Convert XML data into JSON using PHP ?
In this article, we are going to see how to convert XML data into JSON format using PHP. Requirements: XAMPP Server Introduction: PHP stands for hypertext preprocessor, which is used to create dynamic web pages. It also parses the XML and JSON data. XML stands for an extensible markup language in which we can define our own data. Structure of XML:
3 min read
three90RightbarBannerImg