Moment For Technology

Getting started with JavaScript objects using JSON

Posted on Aug. 6, 2022, 1:49 a.m. by Danielle Bowman
Category: The front end Tag: The front end

JavaScript Object Representation (JSON) is a standard format for representing structured data as JavaScript objects, often used to represent and transfer data on web sites

What is a JSON

JSON is a data format that follows JavaScript object syntax, popularized by Douglas Crockford. Although it is based on JavaScript syntax, it is independent of JavaScript, which is why many program environments can read (interpret) and generate JSON.

JSON can exist either as an object for interpreting data in JSON or as a string for transferring JSON data over a network. This is not a big deal -- JavaScript provides a globally accessible JSON object to convert these two types of data.

A JSON object can be stored in its own file, which is basically a text file with a.json extension and [MIME Type]( "MIME type: A MIME type (now properly called "media type", but also sometimes "content type") is a string sent along with a file indicating the type of the file (describing the content format, for example, a sound file might be labeled audio/ogg, Or an image file image/ PNG).

We can already assume that JSON objects are based on JavaScript objects, and this is almost correct. You can write JavaScript objects to JSON data as they are -- strings, numbers, arrays, boars, and other literal objects. This allows you to construct a tree of objects as follows:

  "squadName" : "Super hero squad"."homeTown" : "Metro City"."formed" : 2016."secretBase" : "Super tower"."active" : true."members": [{"name" : "Molecule Man"."age" : 29."secretIdentity" : "Dan Jukes"."powers" : [
        "Radiation resistance"."Turning tiny"."Radiation blast"] {},"name" : "Madame Uppercut"."age" : 39."secretIdentity" : "Jane Wilson"."powers" : [
        "Million tonne punch"."Damage resistance"."Superhuman reflexes"]]}}Copy the code

JSON arrays we said earlier, "We can already assume that JSON objects are based on JavaScript objects, and it's almost true" -- we say almost true because array objects are also legal JSON objects, for example:

[{"name" : "Molecule Man"."age" : 29."secretIdentity" : "Dan Jukes"."powers" : [
      "Radiation resistance"."Turning tiny"."Radiation blast"] {},"name" : "Madame Uppercut"."age" : 39."secretIdentity" : "Jane Wilson"."powers" : [
      "Million tonne punch"."Damage resistance"."Superhuman reflexes"]}]Copy the code

Other Matters needing attention

  • JSON is a pure data format that contains only properties and no methods.
  • JSON requires {} on both ends to make it legal. The safest way to write it is with two brackets, not one.
  • Even a misplaced comma or semicolon can cause a JSON file to fail. You should be careful to check the data you want to use (although computer-generated JSON rarely goes wrong, as long as the generator works). You can verify JSON with an application like JSONLint.
  • JSON allows you to format and store any standard legal JSON data, not just arrays and objects. For example, a single string or number can be a valid JSON object. Not particularly useful though...
  • Unlike JavaScript identifiers that can be used as attributes, only strings can be used as attributes in JSON.

Conversion between object and text

  • Parse (): Accepts a JSON object as a text string and returns the corresponding object.
  • Stringify (): takes an object as an argument and returns a corresponding JSON string.

The parse example:

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

// expected output: 42

// expected output: true

Copy the code

Stringify example: Try typing the following code into your browser's JS console to see what happens:

var myJSON = { "name" : "Chris"."age" : "38" };
var myString = JSON.stringify(myJSON);
Copy the code

JSON. Parse (text [reviver]) syntax

Text Specifies the string to be parsed as a JavaScript value. For JSON syntax, see JSON. Reviver Optional converter that, if passed, can be used to modify the original value generated by parsing before the parse function returns.

If the reviver function is specified, the parsed JavaScript value (parsed value) will be converted once before it is finally returned (return value). To be more specific, The reviver function will be called respectively in a certain order (starting from the innermost level of the attribute, moving up to the top level, that is, the attribute itself). During the call, the object to which the current attribute belongs will be used as this value. The current attribute name and attribute value are passed into the Reviver as the first and second parameters, respectively. If reviver returns undefined, the current attribute will be removed from the owning object. If other values are returned, the returned value will become the new attribute value of the current attribute.

When traversing to the top-level value (the parsed value), the arguments passed to the reviver function will be an empty string "" (because there are no real attributes at this point) and the current parsed value (which may have been modified). The current this value will be {"": }, a special case to be aware of when writing reviver functions. (This function is iterated in the following order: start at the innermost layer and work through the hierarchy.)

JSON.parse('{"p": 5}'.function (k, v) {
    if(k === ' ') return v;     // If you reach the top level, return the attribute value directly,
    return v * 2;              // Otherwise double the value of the property.
});                            // { p: 10 }

JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}'.function (k, v) {
    console.log(k); // Print the current attribute name, so that the traversal order is from inside out,
                    // The last attribute name will be an empty string.
    return v;       // Return the original attribute value, equivalent to no reviver argument passed.
Copy the code

Json.stringify (value[, replacer [, space]]) syntax

Value Is the value to serialize to a JSON string.

Replacer Optional If this parameter is a function, each attribute of the serialized value is converted and processed by the function during serialization; If the parameter is an array, only the property names contained in the array will be serialized into the final JSON string; If this parameter is null or not provided, all attributes of the object are serialized; For a more detailed explanation and example of this parameter, see the article Working with Native JSON Objects.

Example (function)

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  return value;

var foo = {foundation: "Mozilla".model: "box".week: 45.transport: "car".month: 7};
var jsonString = JSON.stringify(foo, replacer);
Copy the code

Example (array)

JSON.stringify(foo, ['week'.'month']);  
/ / '{" week ": 45," month ": 7}', only keep" week "and" month "attribute values.
Copy the code

Space Optionally specifies a blank string for indentation, which is used to beautify the output (pretty-print); If the argument is a number, it represents how many Spaces there are; The upper limit is 10. If the value is less than 1, there are no Spaces. If the parameter is a string (the first 10 characters are taken when the string is longer than 10 characters), the string will be used as a space. If this parameter is not provided (or null), there will be no Spaces.

Use json.stringify with the localStorage example

Sometimes you want to store an object created by the user and recover it even after the browser is shut down. The following example is a sample of how json.stringify works in this case:

// Create a sample data
var session = {
    'screens': [].'state' : true

// Convert to a JSON string using json.stringify
// Then use localStorage to save the session name

// Then how to convert the string generated by json.stringify stored in localStorage in JSON format
var restoredSession = JSON.parse(localStorage.getItem('session'));

// restoredSession now contains objects stored in localStorage
Copy the code


Using JSON

About (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.