Powershell - Add a key in a specific manner to a JSON object

Viewed 18

i have an array converted to a json ($user_data_JSON = $user_data | ConvertTo-Json) in powershell which looks like this

$user_data_JSON
{
  [
    {
        "targetId":  "5007Y00000K5nkjQAB",
        "login":  "login1",
        "password":  "scRHDztkKbO"
    },
    {
        "targetId":  "5007Y00000MNbDvQAL",
        "login":  "login2",
        "password":  "scRHDztkKbO"
    }
  ]
}

But i need to modify it like this with a KEY value on top:

$user_data_JSON
{
    "logins":[
        {
            "targetId":  "5007Y00000K5nkjQAB",
            "login":  "login1",
            "password":  "scRHDztkKbO"
        },
        {
            "targetId":  "5007Y00000MNbDvQAL",
            "login":  "login2",
            "password":  "scRHDztkKbO"
        }
    ]
}

How can I manage to achieve this? I've already tried to create a new array object, add the key and convert it to a json file like this:

$jsonBase = @{}
$list = New-Object System.Collections.ArrayList
$list.Add("Foo")
$list.Add("Bar")
$jsonBase.Add("Data",$list)
$jsonBase | ConvertTo-Json
To get something like this:
{
  "Data": [
    "Foo",
    "Bar"
  ]
}

but when I convert my array to a json again, it looks kind of trunkated:

$jsonBase | ConvertTo-Json -Depth 10
{
    "logins":  [
                   "[\r\n    {\r\n        \"targetId\":  \"5007Y00000K5nkjQAB\",\r\n        \"login\":  \"login1\",\r\n        \"password\":  \"scRHDztkKbO\"\r\n    },\r\n    {\r\n   
     \"targetId\":  \"5007Y00000MNbDvQAL\",\r\n        \"login\":  \"login2\",\r\n        \"password\":  \"scRHDztkKbO\"\r\n    },"
               ]
}

How can I get a propoer JSON object? Thanks

1 Answers

Don't use the JSON (text) representation of your array ($user_data_JSON), use its original, object form ($user_data) to construct a wrapper object with the desired top-level property:

[pscustomobject] @{ logins = $user_data } | ConvertTo-Json -Depth 10

As for what you tried:

If you use a preexisting JSON string as the value of property to be converted to JSON with ConvertTo-Json, it is treated like any other string value, resulting in the representation you saw, with " characters escaped as \" and (CRLF) newlines as \r\n

A simple example:

[pscustomobject] @{ 
  foo = '{ "bar": 
           "baz" }' 
} | ConvertTo-Json

Output (note how the foo property value became a single-line string with " and newlines escaped):

{
  "foo": "{ \"bar\": \n           \"baz\" }"
}
Related