0

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?

3
  • 1
    Just read the file with fs.readFile, run it through JSON.parse, modify it, and write it back with fs.writeFile. Commented Jul 17, 2020 at 6:56
  • @Christian yes I tried this but it gives the file with only the added data. The previous/original data erases away. Commented Jul 17, 2020 at 7:02
  • @Christian This is requires a step to manually update data but I want to add data using a bit of iteration and loops. Commented Jul 17, 2020 at 7:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It overwrites the file data and gives the output as only the modified one. Can you please check once?
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.