Search code examples
arraysjsonpowershelldata-conversion

ConvertTo-JSON falsely parses arrays


This question has also been answered here:

Stackoverflow: Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2

GitHub: ConvertFrom-Json and ConvertTo-Json breaks arrays

Mircrosoft Docs: ConvertTo-JSON

TL;DR

If you save your .json with ConvertTo-JSON and it break it, you may want to speccify the -Depth parameter, as it's default value it 2 and it wont parse nestet objects beyond that.

Original Post:

So I want to load, then save data from a JSON file through a PowerShell skript. The JSON contains an array within an object, which looks like this:

{
    "head": {
        "head2": {
            "data0": "a",
            "data1": "b"
        },
        "head3": {
            "data8": [
                "x",
                "y",
                "z"
            ],
            "data9": "hello"
        }
    }
}

Notice the array "data8".

Now when I load and save the file like so: Get-Content test.json | ConvertFrom-JSON | ConvertTo-JSON I want to end up with the exact same file, since I'm not changing anything. However the result is this:

{
    "head": {
        "head2": {
            "data0": "a",
            "data1": "b"
        },
        "head3": {
            "data8": "x y z",
            "data9": "hello"
        }
    }
}

The "data8" has been reduced to a single string and I struggle to find out why. It seems to happen during the ConvertTo-JSON because when I don't do that yet, It will give me an array of strings containing x,y and z.

E.g. (Get-Content test.json | ConvertFrom-JSON).head.head3.data8 will result in

x

y

z

and (Get-Content test.json | ConvertFrom-JSON).head.head3.data8 -is [array] gives True

Things I've tried:(get-content test.json | convertfrom-json).head.head3.data8

Various encoding methods in test.json, but this even happens when I save the file as utf8 and add -encoding utf8 to Get-Content so I don't believe that is has to do with that.

For the sake of trying, I even added -compress to ConvertTo-JSON which didn't help either.


Solution

  • Okay so apparently PowerShell only parses data up to a depth of 2 by default. So as pointed out Here you have to specify the depth with the depth prameter of ConvertTo-Json