I was trying to append multiple Json object in a single JSON Array using Powershell
From this answer I got the solution
$users = [System.Collections.ArrayList]::new();
#calling some API in a loop Start
$response = $json | ConvertTo-Json
$null = $data.Add($response);
#calling some API in a loop End
$result = @{ Data = $data};
$result | ConvertTo-Json | % { [System.Text.RegularExpressions.Regex]::Unescape($_) } | Out-File 'C:\Jay\inv\$filename.json'
For an instance Lets say the JSON Response from the API is like
{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": [
{
"delegation": 1
}
]
}
Then as per the script my final file i was expecting like
{
"Data" : [
{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": [
{
"delegation": 1
}
]
},
{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": [
{
"delegation": 1
}
]
}
]
}
But I'm getting additional quotation marks like below which makes the error in the json
{
"Data" : [
"{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": [
{
"delegation": 1
}
]
}",
"{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": [
{
"delegation": 1
}
]
}"
]
}
Could someone help to find what is going wrong with the powershell script ?
Update 1
$result = @{ Data = $data | ConvertFrom-Json };
I'm getting the json like
{
"Data" : [
{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": " "
]
},
{
"host": "tet",
"port": 443,
"protocol": "http",
"isPublic": false,
"status": "READY",
"startTime": 1585220081665,
"testTime": 1585220127003,
"engineVersion": "2.1.0",
"criteriaVersion": "2009q",
"endpoints": " "
]
}
]
}
@{ Data = $data};->@{ Data = $data |ConvertFrom-Json};$Jsonis confusing (why would you do$json | ConvertTo-Jsonif it is already json?). Anyways, you probable do not want to convert the object to Json at all at this level. Meaning just:$null = $data.Add($json)-Depth 4toConvertTo-Json