How to add json in javascript

From time to time we need to manipulate JSON data by adding new elements into it. A JSON object is typically more difficult to directly edit as its normally in a string format.

So, how can you add an array element into a JSON Object in JavaScript?

This is done by using the JavaScript native methods .parse()and .stringify()

We want to do this following:

  • Parse the JSON object to create a native JavaScript Object
  • Push new array element into the object using .push()
  • Use stringify() to convert it back to its original format.

Let’s take the following JSON string data as an example:

'{"characters":[{"name":"Tommy Vercetti","location":"Vice City"},{"name":"Carl Johnson","location":"Grove Street"},{"name":"Niko Bellic","location":"Liberty City"}]}'

We have a list of notorious GTA characters in our JSON. Let’s say we want to add one more character:

{"name":"Ken Rosenberg","location":"Vice City"}

First, we need to parse our original JSON data

const obj = JSON.parse(data);

Then we want to add our new character into the parsed object:

obj["characters"].push({ name: "Ken Rosenberg", location: "Vice City" });

With the new character added, our JSON object now looks like this:

{
   "characters":[
      {
         "name":"Tommy Vercetti",
         "location":"Vice City"
      },
      {
         "name":"Carl Johnson",
         "location":"Grove Street"
      },
      {
         "name":"Niko Bellic",
         "location":"Liberty City"
      },
      {
         "name":"Ken Rosenberg",
         "location":"Vice City"
      }
   ]
}

Finally, we want to flip the data variable back into its original stringified JSON format:

data = JSON.stringify(obj);

And there you have it. Remember, that JSON is just a different type of notation so its always available to be transformed back into a proper JavaScript object for data manipulation.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted.

    Example 1: This example adds {“prop_4” : “val_4”} to the GFG_p object by using dot notation.

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            JavaScript |

          Add a key/value pair to JSON object

        </title>

    </head>

    <body style="text-align:center;">

        <h2 style="color:green;">  

                GeeksForGeeks  

            </h2>

        <p id="GFG_up"

           style=" font-weight: bold">

        </p>

        <button onclick="Geeks()">

            Click to add

        </button>

        <p id="GFG_down" 

           style="color:green;

                  font-weight: bold" ;>

        </p>

        <script>

            var GFG_p = {

                prop_1: "val_1",

                prop_2: "val_2",

                prop_3: "val_3"

            };

            var p_up = 

                document.getElementById("GFG_up");

            var p_down = 

                document.getElementById("GFG_down");

            p_up.innerHTML = 

              JSON.stringify(GFG_p);

            function Geeks() {

                GFG_p.prop_4 = "val_4";

                p_down.innerHTML = JSON.stringify(GFG_p);

            }

        </script>

    </body>

    </html>

    Output:

    Example 2: This example adds {“prop_4” : “val_4”} to the GFG_p object by using square bracket notation.

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            JavaScript 

          | Add a key/value pair to JSON object

        </title>

    </head>

    <body style="text-align:center;">

        <h2 style="color:green;">  

                GeeksForGeeks  

            </h2>

        <p id="GFG_up"

           style=" font-weight: bold">

        </p>

        <button onclick="Geeks()">

            Click to add

        </button>

        <p id="GFG_down" 

           style="color:green; 

                  font-weight: bold" ;>

        </p>

        <script>

            var GFG_p = {

                prop_1: "val_1",

                prop_2: "val_2",

                prop_3: "val_3"

            };

            var p_up = 

                document.getElementById("GFG_up");

            var p_down = 

                document.getElementById("GFG_down");

            p_up.innerHTML = 

              JSON.stringify(GFG_p);

            function Geeks() {

                GFG_p["prop_4"] = "val_4";

                p_down.innerHTML = JSON.stringify(GFG_p);

            }

        </script>

    </body>

    </html>

    Output:


    Can I import JSON in JavaScript?

    Make sure the type attribute on the script tag is set to module . Use an import assertion to import the JSON file. For example, import myJson from './example.

    How do I insert a JSON file?

    Click the Add button and select Column. On the Column element, specify values for the Index and Value attributes. Click the Add button in the sub-menu and select Add Same. Repeat the last two steps to add additional columns and elements from the JSON file.

    How do I add more to a JSON object?

    Use Spread syntax to add JSON object to another JSON object in JavaScript. And use the push() method to add a JSON array at end of an array.

    How do I open a JSON file in JavaScript?

    Use the require() Function to Load JSON Files in JavaScript In JavaScript, we can use the require() method to load files and modules. This takes the path of the local file where it has been saved. With the help of the console. log() function, it loads the data in the server and displays it.