Search code examples
jsonpowershellpowershell-3.0

Powershell: Get value of a raw JSON


I have a JSON file which looks like this:

{
    "body": {
        "mode": "raw",
        "raw": "{\n    \"id\": \"middleware://so/998655555{{sguid}}\",\n    \"reference\": \"998655555{{sguid}}\",\n    \"branchCode\": \"1234\"\n }"
    }
}

Now, I want to output the value of e.g. "branchCode".

I tried it with the following PowerShell commands:

$path = "file.json"
$raw = Get-Content $path -raw

$obj = ConvertFrom-Json $raw

$obj.body.raw.branchCode

Unfortunately, I don't get the value. It seems like PowerShell has a problem to retrieve the value from the raw json.

I would be very happy if someone could help me.


Solution

  • The value of "raw" is itself JSON.

    You have to convert from JSON twice.

    $data = Get-Content "file.json" -Raw -Encoding UTF8 | ConvertFrom-Json
    $body = $data.body.raw | ConvertFrom-Json
    $body.branchCode
    

    prints

    1234
    

    Note that you should always explicitly specify an encoding when reading from and writing to text files. For the purposes of JSON (and, frankly, for pretty much every other purpose), UTF-8 is the appropriate choice.

    Unfortunately Get-Content/Set-Content do not default to UTF-8. Save yourself from trouble by always specifying an encoding when working with text files.