I want to add a value to an existing JSON file using PSCustomObject

Asked 2 years ago, Updated 2 years ago, 80 views

Prerequisites/What you want to achieve

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", 
                                    }
                           }
                        ]
            }
         ]
       }

Tried

"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

json powershell

2022-09-30 11:51

3 Answers

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.


2022-09-30 11:51

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


2022-09-30 11:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.