Kevin Brüsch
Kevin Brüsch

Reputation: 11

Powershell json format

I have a question about convert from/to json with powershell. I need a json with a specific format (for a REST Call) but if I do an convertfrom-json and convertto-json the format is wrong and I don't know how I can change it. This is the original format:

{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  [1522678260000],
                                 "values":  ["compliant"],
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

and if I do an converfrom-json ... then I change some values and then I do an convertto-json the format is without the brackets:

{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  "1522678260000",
                                 "values":  "compliant",
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

Thanks!

Upvotes: 0

Views: 441

Answers (1)

iRon
iRon

Reputation: 23623

The arrays are flattened by the ConvertTo-Json cmdlet because of the -Depth parameter which is set to 2 by default. If you higher the -Depth it will resolve your issue:

PS C:\> $a = ConvertFrom-JSON @'
>> {
>>     "property-content":  [
>>                              {
>>                                  "statKey":  "Test|Test1",
>>                                  "timestamps":  [1522678260000],
>>                                  "values":  ["compliant"],
>>                                  "others":  "",
>>                                  "otherAttributes":  ""
>>                              }
>>                          ]
>> }
>> '@
PS C:\> $a | convertTo-JSON -Depth 5
{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  [
                                                    1522678260000
                                                ],
                                 "values":  [
                                                "compliant"
                                            ],
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

Upvotes: 3

Related Questions