Reputation: 125
I have two JSON objects and I am trying to build one object out of it. I am using an example here, but the properties/names are dynamic.
I have looked into JOIN function, MERGE, Combine-Object none of them seems to do what I want. As they either replace the values with the one or give me random results.
This is my example,
$aVar = '{ "oldEmployees" : [ { "firstName": "Jane", "lastName": "Doe" }, { "firstName": "John", "lastName": "Doe" } ] }'
$bVar = '{ "newEmployees" : [ { "firstName": "Joe", "lastName": "Doe" } ] }'
I would like to have one JSON as,
{
"oldEmployees": [
{
"firstName": "Jane",
"lastName": "Doe"
},
{
"firstName": "John",
"lastName": "Doe"
}
],
"newEmployees": [
{
"firstName": "Joe",
"lastName": "Doe"
}
]
}
BACKGROUND: I am using a JSON object to deploy multiple resources in Azure DevOps pipeline using an ARM template. I have hit a point where I am limited to use Powershell script to combine multiple variables due to the size limit on the Azure Pipeline Variables to a max of 4K characters.
Upvotes: 3
Views: 3926
Reputation: 4428
This will give you the exact JSON that you seek:
$combinedObject = New-Object -TypeName PSObject -Property @{
oldEmployees = @($aVar | ConvertFrom-Json | Select-Object -ExpandProperty oldEmployees)
newEmployees = @($bVar | ConvertFrom-Json | Select-Object -ExpandProperty newEmployees)
} | ConvertTo-Json
It's the same approach as Panomosh's answer, except that instead of using an array, I used a property map. This prevents the output from having an array.
Upvotes: 4
Reputation:
Simply pipe your definition to |Convertfrom-Json
$aVar = '{ "oldEmployees" : [ { "firstName": "Jane", "lastName": "Doe" }, { "firstName": "John", "lastName": "Doe" } ] }' |ConvertFrom-Json
$bVar = '{ "newEmployees" : [ { "firstName": "Joe", "lastName": "Doe" } ] }'|ConvertFrom-Json
$aVar,$bVar|ConvertTo-Json
The result is ugly formatted with PSv5 it get's better with core.
[
{
"oldEmployees": [
"@{firstName=Jane; lastName=Doe}",
"@{firstName=John; lastName=Doe}"
]
},
{
"newEmployees": [
"@{firstName=Joe; lastName=Doe}"
]
}
]
Upvotes: 4
Reputation: 902
you are going to have to turn both of the JSON into powershell objects, combine them, and then turn them back into JSON. In the example above, powershell will just see them as strings.
You can do this like so:
$container = @()
$container += ConvertFrom-Json '{ "oldEmployees" : [ { "firstName": "Jane", "lastName": "Doe" }, { "firstName": "John", "lastName": "Doe" } ] }'
$container += ConvertFrom-Json '{ "newEmployees" : [ { "firstName": "Joe", "lastName": "Doe" } ] }'
$combinedObject = $container | ConvertTo-Json
now if you view $combinedObject
you will see:
[
{
"newEmployees": [
"@{firstName=Joe; lastName=Doe}"
]
},
{
"oldEmployees": [
"@{firstName=Jane; lastName=Doe}",
"@{firstName=John; lastName=Doe}"
]
}
]
Upvotes: 3