Trying to append an array to a json object but having formatting issues. after appending the desired output format is not a json or as expected.
i have a json object, then converted a json object to custom nested object then trying to append new objects to array which is where am getting formatting issues.
help on this is really appreciated.
below is code
$json = @'
{
"scope": {
"entities": [],
"matches": [
{
"type": null,
"managementZoneId": null,
"mzId": null,
"tags": [
{
"context": "CONTEXTLESS",
"key": "DetectedName",
"value": ""
}
],
"tagCombination": "AND"
}
]
}
}
'@
# Convert from JSON to a nested custom object.
$obj = $json | ConvertFrom-Json
# Append new objects to the array.
$obj.scope.matches += [pscustomobject] @{ type = 'null'
managementZoneId = 'null'
mzId = 'null'
tags = '[{ "context": "CONTEXTLESS", "key": "DetectedName", "value": "naae22let1ci1.ktb.kontoorbrands.com" }]'
tagCombination = 'AND' }
# Convert back to JSON.
$obj | ConvertTo-Json -Depth 100"
output is:
{
"scope": {
"entities": [],
"matches": [
{
"type": null,
"managementZoneId": null,
"mzId": null,
"tags": [
{
"context": "CONTEXTLESS",
"key": "DetectedName",
"value": ""
}
],
"tagCombination": "AND"
}
{
"type": "null",
"managementZoneId": "null",
"mzId": "null",
"tags": "[{ \"context\": \"CONTEXTLESS\", \"key\": \"DetectedName\", \"value\": \"naae22let1ci1.ktb.kontoorbrands.com\" }]",
"tagCombination": "AND"
}
]
}
}
desired output :
$obj | ConvertTo-Json -Depth 100
{
"scope": {
"entities": [
],
"matches": [
{
"type": null,
"managementZoneId": null,
"mzId": null,
"tags": [
{
"context": "CONTEXTLESS",
"key": "DetectedName",
"value": ""
}
],
"tagCombination": "AND"
},
{
"type": null,
"managementZoneId": null,
"mzId": null,
"tags": [
{
"context": "CONTEXTLESS",
"key": "DetectedName",
"value": ""
}
],
"tagCombination": "AND"
}
]
}
}