I would like to read the json file in ConvertFrom-Json in PSCustomObject, add the value, and output it as follows, but I don't know what command to execute.
InputJson
{
"hoge1": {
"hoge2": [
{
"hoge3": [
]
}
]
}
OutputJson
{
"hoge1": {
"hoge2": [
{
"hoge3": [
{"foo1":{
"foo2": "XXXX",
"foo3": "XXXX",
}
}
]
}
]
}
"key:value" for foo2 and foo3 could be done with the following command:
However, I don't know how to add foo1 (object as json calls it).
$d=New-Object's system.collections.generic.dictionary [string, string]'
$d.Add ("foo2", "XXXX")
$d.Add ("foo3", "XXXX")
$PSCustomObject.hoge1.hoge2.hoge3+=$d
If it is okay to use it as a PSCustomObject instead of a complete Json structure, I think it can be reproduced below.Does this meet the requirements?
$base=@"
{
"hoge1": {
"hoge2":"
}
}
"@
$child=@"
{
"hoge3":"
}
"@
$grandchild=@"
{
"foo1": {
"foo2": "XXXX",
"foo3": "XXXX"
}
}
"@
$json1 = ConvertFrom-Json$base
$json2 = ConvertFrom-Json$child
$json3 = ConvertFrom-Json$grandchild
$json1.hoge1.hoge2=@($json2)
$json1.hoge1.hoge2[0].hoge3=@($json3)
Output
PSC:\Windows\System32>$json1.hoge1.hoge2[0].hoge3[0].foo1.foo2
XXXX
If you need to save it as a Json structure, the middle array cannot be ConvertTo-Json, so you can either classify it separately and convert it with JsonQueryStringConverter, configure it in XML and convert it with JsonReaderWriterFactory, or incorporate a self-converting mechanism.
Isn't it like this?
$x=catj.json | ConvertFrom-Json
$d = new-object "system.collections.generic.dictionary [string, string]"
$d.add("foo2", "XXXX")
$d.add("foo3", "xxxx")
$foo1=[PSCustomObject]@{"foo1"=$d}
$x.hoge1.hoge2[0].hoge3=@($foo1)
$x | ConvertTo-Json-Depth 100>>j2.json
$PSCustomObject=Get-Content./input.json | ConvertFrom-Json
$PSCustomObject.hoge1.hoge2[0].hoge3+=@{foo1=@{foo2='XXXX';foo3='XXXX'}
ConvertTo-Json$PSCustomObject-Depth100
can be achieved on the .
PowerShell doesn't care about data types.
The exact .NET System.Object[]
array allows you to mix any data type.In addition, ConvertTo-Json
uses JavaScriptSerializer
as described in the Note.JavaScriptSerializer
accepts any object and prints public properties in JSON format.As a result, any type is fine as long as you have public properties in the desired format.
For example, using PSCustomObject
[PSCustomObject]@{foo1=[PSCustomObject]@{foo2='XXXX';foo3='XXXX'}
can be written as .However, the JavaScriptSerializer
expands as expected for classes with IDictionary
as the object type of JSON.That's why
@{foo1=@{foo2='XXXX';foo3='XXXX'}}
provides sufficient results.
© 2024 OneMinuteCode. All rights reserved.