Reputation: 3081
I am a newbie to Powershell and I couldn't find this on googling but how do I build a json structure with an array inside? Is it through a custom object? Have been a bit confused by the syntax that I have seen online and not sure what is the recommended way to do it. Eventually I need to be able to save it to a JSON file too.
json_ret = {
"a": 4,
"b": [ {"c" : 5, "d": "text", "e": "foo"}]
}
Upvotes: 5
Views: 18250
Reputation: 101
If using variables, then can create body including array like shown below, where $text is the variable. No need to user ConvertTo-Json and can easily copy the body from postman directly.
$text = "ABC"
# Post Body
$body = @"
{
"name" = "$text",
"description" = "$text",
"myArray": [
{
"id": "2c91808680d3c34b0180dc81d78c21e9",
"type": "myType",
"name": "myName"
}
]
}
"@
$body
Upvotes: 2
Reputation: 437090
If you want to create the JSON document directly, as a string, it's simplest to use a verbatim here-string:
$json_ret = @'
{
"a": 4,
"b": [ {"c" : 5, "d": "text", "e": "foo"}]
}
'@
You can easily save that to a file with $json_ret | Set-Content file.json
, for instance.
By contrast, if you want to construct your data as an object graph first, to be converted to JSON with ConvertTo-Json
later, see Wasif_Hasan's helpful answer.
As for what you tried:
An unquoted { ... }
construct is a script block, which is a piece of PowerShell code for later invocation on demand - and the contents of your JSON document happen not to constitute valid PowerShell code, causing construction of the script block to fail.
Upvotes: 4
Reputation: 15470
Yes you can build a json object through a PSCustomObject:
[PSCustomObject]@{
a = 4
b = @([ordered]@{
c = 5
d = "text"
e = "foo"
})
} | ConvertTo-Json
First we create PSObject using its type accelerator PSCustomObject.
Then we define the root key and value "a", and we have to create an array inside "b".
The @()
statement creates an array, but we can't we create key-value pairs in array. So we use @{}
to create hashtable. Before it [ordered]
flag says the hashtable to keep the exact structure as we have created it.
Then we define the array values, and after that close the internal array-hashtable.
Now we end the PSCustomObject and pipe it ConvertTo-Json
. Now you get a converted json.
Footnotes
[PSCustomObject]@{
a = 4
b = @([ordered]@{
c = 5
d = "text"
e = "foo"
})
} | ConvertTo-Json | Out-File "Filepath"
$variable = ([PSCustomObject]@{
a = 4
b = @([ordered]@{
c = 5
d = "text"
e = "foo"
})
} | ConvertTo-Json)
Upvotes: 6