LGEYH
LGEYH

Reputation: 63

Modify existing json file using nodejs

I have a json file named a1.json->(It has the following structure)

{ "Key1" :
[ { 
    "Key11" : "Value11" , 
    "Key12" : "Value12"
  },
 {
    "Key21" : "Value21" , 
    "Key22" : "Value22"
 }
]
}

I am iterating through a data file which has certain values. If the values match i will have to add an extra key to that particular dictionary only. For example-

{ "Key1" :
    [ { 
        "a" : "A1" , 
        "b" : "B1"
      },
     {
        "a" : "A2" , 
        "b" : "B2"
     }
    ]
}

I want to add a key value pair in that list whose key value "a" is "A1". So the final result will look something like this-

{ "Key1" :
    [ { 
        "a" : "A1" , 
        "b" : "B1" ,
        "New_Key_Array" : 
                [
                     {
                        "Found" : "yes",
                        "Correctness" : "true"
                     }
                ]
      },
     {
        "a" : "A2" , 
        "b" : "B2"
     }
    ]
 } 

How do I go about this. I am a bit new to JSON formatting and still learning how to edit existing JSON files?

Upvotes: 0

Views: 89

Answers (2)

Wolfetto
Wolfetto

Reputation: 1130

I am providing a code snippet for your problem:

let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
console.log("JSON at the beginning:\n", j);
j.Key1.forEach((element, index) =>{
  if(element.a === "A1"){
    //Here I have to edit the JSON obj
    j.Key1[index]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
  }  
}); 
console.log("JSON edited:\n ",j);
let objString =JSON.stringify(j);

Upvotes: 0

jonasdev
jonasdev

Reputation: 736

You can use JSON.parse() to parse your json file/string into a JavaScript object. In your example:

let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');

To add a new key to your object, it's possible with native JavaScript code, if that's what you want:

j.Key1[0]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];

To convert back into json formatted string, you can use the JSON.stringify() function.

Upvotes: 1

Related Questions