JSON and JSON object in javaScript

Cover Image for JSON and JSON object in javaScript
Ali Bentaleb
Ali Bentaleb

JSON stands for JavaScript Object Notation. It's an open standard file and data interchange format that is independent from any programming language, it has also been used a lot lately in REST style.

JSON two main basics are:
  • A collection of name and value pairs.
  • An ordered list of values or collections.

JSON data structures

JSON resembles JavaScript since it is a subset of it and is based on the 1999 ECMA-262 specification, you can check more about ECMAScript in this article, it also includes several data structure types, for instance you can define:

- **Null**: the _null_ value. - **Number**: is similar to number in other languages, and it does not need a quote or double quotes, also the hexadecimal and the octal formats are not used.
  • String: is any String in any other language, and it should be wrapped in double quotes.
  • Object: is an unordered set of name and value pairs. An object should be wrapped in curly braces, the name is a String that should be wrapped in double quotes, and name value pairs are separated by a colon :, also each pair should be separated by a comma.
  • Boolean: either true or false and does not need quotes.
  • Array: is an ordered list of values, and it is wrapped inside brackets.
  • Value in Object or Array: the value in an object or an array can be anything from a String that should be wrapped in double quotes, a number, a Boolean or null, and an object or an array.
We can also create nested structures, like an array value, and each value of the array is an object. Let’s see this example to learn more:
{
    "firstName": "Ali",
  "age": 31,
  "isAlive": true,
  "bigArray": [
    {

      "id": "hello",
      "someNumber": 50,
      "idiot":null,
      "nestedArray": [
        "String value",
    {"anothervalue": 3} ,
        455
      ]
    },

    {"manyother":"yes"}, "simpleValue"],
    "anotherOne": {"name":"value"}
}

We present above multiple examples of possible combination in a JSON String, The first three lines show primitives use like number, Boolean and String, the _bigArray_ has objects and array on it, and the last line is a name with an object as a value.

Remember that:

  • Any name is a String surrounded by double quotes.
  • Its value could be anything from primitives like number, Boolean, null, an object or an objects array, and of Course you can nest types as long as you respect the syntax.
  • The value cannot be a method like you would do in JavaScript.

Accessing JSON through JavaScript

You can access directly a JSON object with JavaScript by either:

- **using the dot notation**: specify the dot after the object name. - **using the bracket notation**: specify the brackets after the object name with the attribute name inside the brackets.

Below a sample:

const jsonSample = { "name": "someName", "nextThing": { myKey: "myValue" } };

//the dot notation

console.log(jsonSample.nextThing.myKey); //prints out myValue

//the bracket notation
console.log(jsonSample["nextThing"]["myKey"]); //prints out myValue

We are accessing the same value with two different methods, one is with the dot notation and the other with the bracket notation, make sure to put the double quotes between brackets.

Parse JSON with JSON.parse and optional reviver

The ECMA has defined the object JSON with its method parse; this one is useful in case you would like to turn the JSON String into an ES language value.

The method syntax is JSON.parse ( text [ , reviver ] ) where the reviver is an optional parameter.

JSON.parse with text

To parse the JSON with JSON.parse, the method takes in the JSON text, in our case, to make it text, we put it between backticks like that:

To test this, create a file.js file and put inside this content, and run it using _node file.js

const jsonSample = `{ "name": "someName", "nextThing": { "myKey": "myValue"} }`;

console.log(JSON.parse(jsonSample));
// the results are { name: 'someName', nextThing: { myKey: 'myValue' } }

The text has been transformed to an ES value; we can notice the names without double quotes and the values with simple quotes which is OK in JavaScript objects.

JSON.parse with reviver

The reviver is an optional parameter to use in JSON.parse, it is a function that takes a key and value pairs produced by the parse. It can then filters and transform the results and return the filtered value instead of the original value. Let’s see the same sample but now with the reviver to clear up things:

const jsonSample = `{ "name": "someName", "nextThing": { "myKey": "myValue"} }`;

JSON.parse(jsonSample, (key, value) => {
  if (key === "name") console.log(value);
});
//prints out someName

Our reviver has looped on each key value pair and checks if the key equals name, it prints then the result which is in our case someName.

Convert JavaScript Object to JSON with JSON.stringify

We can do the other way around by converting an ES value into a JSON by using the JSON.stringify method.

The method can takes in a JavaScript object or more parameters, the complete syntax is : JSON.stringify ( value [ , replacer [ , space ] ] ).

JSON.stringify with value

The sample below shows how JSON.stringify turns out our esValue to a valid JSON, which can be then sent to a REST Web service using JSON for example.

const esValue = { name: "someName", nextThing: { myKey: "myValue" } };

console.log(JSON.stringify(esValue));
//{"name":"someName","nextThing":{"myKey":"myValue"}}

JSON.stringify with replacer and space

JSON.stringify ( value [ , replacer [ , space ] ] ).

  • The optional replacer parameter can be a function that alters the way objects and arrays are stringified, or could be array of Strings and Numbers that filter which properties to be stringified.
  • The optional space parameter is either a String or Number that helps in putting white spaces before name to improve human readability.

In the below we have used replacer as an array to filter only same names.

const esValue = { first: "someName", nextThing: { myKey: "myValue" } };

console.log(JSON.stringify(esValue, ["first"], 4));
//the 4 is how much space between first line and the first name
// the replacer here is an array which contains which name to choose
/* 
 {
    "first": "someName"
}

 */

The replacer parameter is an array, and space parameter is a number with value 4, so it makes 4 spaces before the name, and we choose first to be printed out.

The three dots in javascript -...