I know this type of questions has been asked but I cant find the exact answer to my specific question – if there is one please let me know and apologies…
I have two json files and need to merge/combine them so I end up with a final file
Example
File 1:
{
"ONE": {
"A": "value1",
"B": "value2",
"C": "value3"
},
"TWO": {
"A": "value4",
"B": "value5",
"C": "value6"
}
}
File 2:
{
"ONE": {
"D": "valueY"
},
"TWO": {
"D": "valueX"
}
}
Final File:
{
"ONE": {
"A": "value1",
"B": "value2",
"C": "value3",
"D": "valueY"
},
"TWO": {
"A": "value4",
"B": "value5",
"C": "value6",
"D": "valueX"
}
}
I can do a basic merge OK – but cant seem to figure out how to ‘insert’ or ‘add’ the "D" value into the first file so they are all in the final file?
Any advice would be great
Thanks
3
Answers
You might use the
Merge()
method of theNewtonsoft.Json.Linq
Namespace for this:Here is a solution in Python3:
You’ll want to convert these to objects that PowerShell can more easily manage.
Not sure where the input is coming from – but you get the picture.
Now turn them into hashtables
As long as the names are the same "ONE, TWO" in your json files, then when you iterate through the 2nd file, the keys will align, and add the values:
fun times – now everything has been ‘merged’ into $file1_hash. So convert it back to json.
OUTPUT: