JSON in Javascript. Code examples open

JSON in Javascript. Code examples

JSON (JavaScript Object Notation) is a lightweight data storage format. JSON objects are very similar to JavaScript objects, especially since JSON is a subset of JavaScript. At the same time, it is important to distinguish between them: JavaScript is a programming language, while JSON is a data format.

JSON supports three data types: primitive values, objects, and arrays.

Primitive values represent standard strings, numbers, null, booleans true, and false.

Objects represent a set of simple data, other objects, and arrays. For example, a typical JSON object:

{
   "name": "Tom",
   "married": true,
   "age": 33
}

In javascript, this object would correspond to the following:

var user = {
   name: "Tom",
   married: true,
   age: 33
}

JSON cannot store functions, variables like JavaScript objects.

{
    "name": "Alexander",
    "married": false,
    "age": 33,
    "company": {
        "name": "Microsoft",
        "address": "USA, Redmond"
    }
}

Arrays in JSON

Arrays in JSON are similar to javascript arrays and can also store simple data or objects:

    ["Alexander", false, 33]

Array of objects:

    [{
    "name": "Alexander",
    "married": false,
    "age": 33
},{
    "name": "Bob",
    "married": true,
    "age": 25
}]

Javascript object to JSON object

To serialize a JavaScript object to JSON, use the JSON.stringify() function:


    var user = {
    name: "Alexander",
    married: false,
    age: 33
	
};

    var serializedUser = JSON.stringify(user);
    document.write(serializedUser); // {"name":"Alexander","married":false,"age":33}

For the reverse operation – deserialization or parsing of a JSON object in JavaScript, the JSON.parse() method is used:

    var user = {
        name: "Alexander",
    married: false,
    age: 33
};
    var newUser = JSON.parse(serializedUser);
    document.write(newUser.name); //Alexander
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation