JavaScript JSON Parsing

What is JSON?

JSON is an abbreviation for JavaScript Object Notation. JSON is an easily deployable data-interchange format that is fast and simple to scan and create for data exchange between server and client.

JSON, like XML, is a text-based format that is simple to produce and comprehend for both people and machines; but, unlike XML, JSON data structures consume less bandwidth than their XML counterparts.

JSON is built on two fundamental structures:

  • Object:

    This is defined as an unsorted set of key/value pairs (i.e. key:value). Each item is separated by a left curly bracket and a right curly bracket. A comma, separates several key/value pairs.

  • Array:

    This is defined as a sequence of values. An array is denoted with a left bracket and terminates with a right bracket. A comma, separates the values.

Parameter identifiers or keys have always been strings in JSON, although the value can be a text, integer, true or false, null, or even an object or an array. Strings must be surrounded by double quotes ” and may contain escape characters such as \n, \t, and \

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Parse JSON Object in JavaScript< /title>
< /head>
< body>
< script>
    /* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
varjson = `{
        "book": {
            "name": "Harry Potter and the Goblet of Fire",
            "author": "J. K. Rowling",
            "year": 2000,
            "genre": "Fantasy Fiction",
            "bestseller": true
        }
    }`;

    // Converting JSON object to JS object
varobj = JSON.parse(json);
console.log(obj);
< /script>
< p>< strong>Note:< /strong> Please check out the browser console by pressing the f12 key on the keyboard.< /p>
< /body>
< /html>

In context, consider the following JSON array example:

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Parse JSON Array in JavaScript< /title>
< /head>
< body>
< script>
    /* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
varjson = `{
        "colors": [
            "Red",
            "Green",
            "Blue",
            "Yellow"
        ]
    }`;

    // Converting JSON object to JS object
varobj = JSON.parse(json);
console.log(obj);
< /script>
< p>< strong>Note:< /strong> Please check out the browser console by pressing the f12 key on the keyboard.< /p>
< /body>
< /html>

A data-interchange format seems to be a file extension that is used to communicate data between platforms and operating systems. JSON is the most widely used and lightweight data-transfer format for online applications.

Parsing JSON Data in JavaScript

Using the JSON.parse() function in JavaScript, you may simply parse JSON data received from a web server. This function parses a JSON string and creates the JavaScript value or object that the string describes. A syntax error will be returned if the specified text is not valid JSON.

Assume we’ve got the JSON-encoded string below from a web server:

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Parse JSON String in JavaScript< /title>
< /head>
< body>
< script>
    // Store JSON data in a JS variable
varjson = '{"name": "Ajeet", "age": 26, "country": "India"}';

    // Converting JSON object to JS object
varobj = JSON.parse(json);
console.log(obj);
< /script>
< p>< strong>Note:< /strong> Please check out the browser console by pressing the f12 key on the keyboard.< /p>
< /body>
< /html>

We can now easily use the JavaScript JSON.parse() function to transform this JSON string into a JavaScript object and access individual values using dot notation (. ), as seen below:

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Convert JSON String to JavaScript Object and Access Individual Values< /title>
< /head>
< body>
< script>
    // Store JSON data in a JS variable
varjson = '{"name": "Ajeet", "age": 26, "country": "India"}';

    // Converting JSON-encoded string to JS object
varobj = JSON.parse(json);

    // Accessing individual value from JS object
document.write(obj.name + "< br>"); // Prints: Peter
document.write(obj.age + "< br>"); // Prints: 22
document.write(obj.country); // Prints: United States
< /script>
< /body>
< /html>

Output

Ajeet
26
India

Parsing Nested JSON Data in JavaScript

JSON objects and arrays could be nested as well. A JSON object can include any number of additional JSON objects, collections, nested arrays, JSON object arrays, and others. In JavaScript, the following example shows how to read a nested JSON object and retrieve all of its values.

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Parse Nested JSON Data in JavaScript< /title>
< /head>
< body>
< script>
    /* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
varjson = `{
        "book": {
            "name": "Harry Potter and the Goblet of Fire",
            "author": "J. K. Rowling",
            "year": 2000,
            "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"],
            "genre": "Fantasy Fiction",
            "price": {
                "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11"
            }
        }
    }`;

    // Converting JSON object to JS object
varobj = JSON.parse(json);

    // Define recursive function to print nested values
functionprintValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
            } else {
document.write(obj[k] + "< br>");
            };
        }
    };

    // Printing all the values from the resulting object
printValues(obj);

document.write("< hr>");

    // Printing a single value
document.write(obj["book"]["author"] + "< br>");  // Prints: J. K. Rowling
document.write(obj["book"]["characters"][0] + "< br>");  // Prints: Harry Potter
document.write(obj["book"]["price"]["hardcover"]);  // Prints: $20.32
< /script>
< /body>
< /html>

Output

Harry Potter and the Goblet of Fire
J. K. Rowling
2000
Harry Potter
Hermione Granger
Ron Weasley
Fantasy Fiction
$10.40
$20.32
$4.11
________________________________________
J. K. Rowling
Harry Potter
$20.32

Encoding Data as JSON in JavaScript

During an Ajax conversation, a JavaScript object or value from your code may need to be transmitted to the server. For this reason, JavaScript offers the JSON.stringify() function, which turns a JavaScript value to a JSON string, as demonstrated below:

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Convert JavaScript Object to JSON string< /title>
< /head>
< body>
< script>
    // Sample JS object
varobj = {"name": "Ajeet", "age": 26, "country": "India"};

    // Converting JS object to JSON string
varjson = JSON.stringify(obj);
document.write(json);
< /script>
< /body>
< /html>

Output

{“name”:”Ajeet”,”age”:26,”country”:”India”}

Note:
Although JavaScript and JSON objects appear to be quite similar, actually are not. In JavaScript, for example, objects property identifiers can be wrapped in single quotes (‘…’) or double quotations (“…”), or they can be omitted entirely. However, all property names in JSON must be wrapped in double quotes.

Stringify a JavaScript Array

Similarly, users could transform JavaScript arrays to JSON strings, as shown below:

Example

< !DOCTYPE html>
< html lang="en">
< head>
< meta charset="utf-8">
< title>Convert JavaScript Array to JSON string< /title>
< /head>
< body>
< script>
    // Sample JS array
vararr = ["Red", "Green", "Blue", "Yellow", "Pink"];

    // Converting JS array to JSON string
varjson = JSON.stringify(arr);
document.write(json);
< /script>
< /body>
< /html>

Output

[“Apple”,”Banana”,”Mango”,”Orange”,”Papaya”]

Copyright 1999- Ducat Creative, All rights reserved.

Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan.