Working with JSON in PowerShell
Cmdlet for working with JSON
JSON -> Object | Object -> JSON |
---|---|
ConvertFrom-Json | ConvertTo-Json |
Create an object, convert it to JSON format, and output a file
PS> $hash1 = [ordered]@{Key1="AAA";Key2="BBB"}
PS> $hash2 = [ordered]@{Key1="CCC";Key2="DDD"}
PS> $object = [pscustomobject]@(
>> $hash1
>> $hash2
>> )
>>
PS> $object | ConvertTo-Json | Out-File sample.json -Encoding utf8
PS> Get-Content .\sample.json
[
{
"Key1": "AAA",
"Key2": "BBB"
},
{
"Key1": "CCC",
"Key2": "DDD"
}
]
PS> $object2 = [pscustomobject]@{
>> Hash1 = $hash1
>> Hash2 = $hash2
>> }
>>
PS> $object2 | ConvertTo-Json | Out-File sample2.json -Encoding utf8
PS> Get-Content .\sample2.json
{
"Hash1": {
"Key1": "AAA",
"Key2": "BBB"
},
"Hash2": {
"Key1": "CCC",
"Key2": "DDD"
}
}
Based on the JSON file, convert it to an object, edit it, and add members to it
Use Add-Member to add a member.
# Prepare text.json
PS> $hash = [ordered]@{Text="Text";Num=100}
PS> $hash | ConvertTo-Json | Out-File test.json -Encoding utf8
PS> Get-Content ./test.json
{
"Text": "Text",
"Num": 100
}
# Convert, edit, and add members to an object based on a JSON file
PS> $obj = Get-Content ./test.json -Raw | ConvertFrom-Json
PS> $obj
Text Num
---- ---
Text 100
PS> $obj.Num++
PS> $obj
Text Num
---- ---
Text 101
PS> $obj.Text = $obj.Text + "Add"
PS> $obj
Text Num
---- ---
TextAdd 101
PS> $obj | Add-Member -MemberType NoteProperty -Name Text2 -Value "Text2"
PS> $obj
Text Num Text2
---- --- -----
TextAdd 101 Text2
PS> $obj | ConvertTo-Json | Out-File test2.json -Encoding utf8
PS> Get-Content ./test2.json -Encoding UTF8
{
"Text": "TextAdd",
"Num": 101,
"Text2": "Text2"
}