Friday, October 21, 2016

Parsing a nested JSON object using PowerShell

Parsing a JSON object using PowerShell can give quick and fast results without too much coding and navigating objects and this is especially true in the case of nested JSON objects.

For example consider this example:
{
  "name": "donut",
  "image":
    {
    "fname": "donut.jpg",
    "w": 200,
    "h": 200
    },
  "thumbnail":
    {
    "fname": "donutThumb.jpg",
    "w": 32,
    "h": 32
    }
}

In order to parse this using PowerShell you formulate this in a Here string and use the ConverstFrom-JSON cmdlet. The rest is easy as you see in this:


JSONNested_01

Compare with this method using a stored procedure in SQL Server.

This next one appeared in StackOverflow.com. The question was, how to get to the value item of slots (which is req1) in the following JSON formmated string.

{"request": {
  "locale": "en-US",
  "timestamp": "2016-09-25T00:36:14Z",
  "type": {
    "name": "request",
    "slots": {
      "RequestTypeItem": {
        "name": "RequestTypeItem",
        "value": "req1"
      }
    }
  }
}
}

One of the answers using JavaScript can be found here. It is correct and gets you to the value as 'req1'.

However, PowerShell provides quite an elegant answer using the ConvertFrom-JSON cmdlet as shown here:


NestedJson_2.png