Friday, October 7, 2016

How do you convert a JSON file to a custom object using PowerShell?

The syntax for converting a JSON formatted string to a custom object is the following:
------
Parameter Set: Default
ConvertFrom-Json [-InputObject] [ ]

-----
ConvertFrom-Json cmdlet converts a JavaScript Object Notation (Json) formated string to a PSCustomObject which has a property for each field in the JSON string.

Read more here:
https://technet.microsoft.com/en-us/library/hh849898.aspx

OK. Let us take a practical example.

Here is a JSON formatted Key-value pairs.
-----------
[  {
  "color": "red",
   "value":"#f00"
 },
 {
   "color":"green",
    "value":"#0f0"
 },
 {
           "color":"blue",
   "value":"#00f"
 },
 {
   "color":"cyan",
  "value":"#0ff"
 }
]
-----------
Now we declare a variable to take the JSON formatted string in a Here-String as shown:
------------
$data=@'
 [  {
  "color": "red",
   "value":"#f00"
 },
 {
   "color":"green",
    "value":"#0f0"
 },
 {
           "color":"blue",
   "value":"#00f"
 },
 {
   "color":"cyan",
  "value":"#0ff"
 }
]
'@
-------------
The above is the correct format that PowerShell would accept for conversion into a JSON object.
With this Here-String in hand you just use the cmdlet as shown:
--------------

ConvertFromJSON.jpg

Now you can use this obejct to find items such as number of segments, items by number or write out the data as shown.


ConvertFromJSON2.jpg

No comments: