Consider I have an array
let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}
I want to append json1 to first item of array1 so the resultant looks like
array1 = [{a:1, b:2, c:3, d:4}, {e:5, f:6}]
I am sure push doesn't work here. I am not sure how to proceed further.
Append file creates file if does not exist. But ,if you want to append JSON data first you read the data and after that you could overwrite that data. We have to read the data, parse, append, and then overwrite the original file because of the JSON format.
Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .
Steps for Appending to a JSON FileRead the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition.
You can use spread operator
let array1 = [{a:1, b:2}, {e:5,f:6}];
let json1 = {c:3, d:4};
array1[0] = {...array1[0], ...json1};
console.log(array1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With