I need to combine 2 json files with powershell that both have unique ID.
Json1
[
{
"id": "1",
"tags": {
"tag1": "value1",
"tag2": "value2"
}
},
{
"id": "2",
"tags": {
"tag1": "value1",
"tag2": "value2",
"tag3": "value3",
"tag4": "value4"
}
}
]
Json2
[
{
"ID": "1",
"Name": "name1",
"State": "Enabled"
},
{
"ID": "2",
"Name": "name2",
"State": "Disabled"
}
]
And the result should look like that:
[
{
"ID": "1",
"Name": "name1",
"State": "Enabled",
"tags": {
"tag1": "value1",
"tag2": "value2"
}
},
{
"ID": "2",
"Name": "name2",
"State": "Disabled",
"tags": {
"tag1": "value1",
"tag2": "value2",
"tag3": "value3",
"tag4": "value4"
}
}
]
Also it would be nice if new file could be converted to csv i tried ConvertTo-CSV but output was unusable.
Assuming you're only interested in matching pairs and both documents contain only objects with unique
IDvalues, the easiest way is to pick any of them and built an index table - either manually using a hashtable/dictionary, or by usingGroup-Object -AsHashtable:Now you can iterate over the objects in the second document and use the index table to quickly fetch the corresponding tags:
Using
ConvertTo-Jsonon thetagsobject gives you a string value that you can later convert back to the originaltagsobject.If you only need the tag values, change the property expression to
If you want the tag names and values as bareword tokens, do:
If you only need the tag values, change the property expression to