Sunday, 2 December 2018

JSON Requests in PowerShell

PowerShell is extremely powerful. I am a trainer and consultant in various technologies like PowerShell, SharePoint, Javascript etc and no matter what the technology is, what is crucial for any technology? DATA

Data can be exchanged in various formats like Xml, Variables in parameters in URL.

What is the most recent way to exchange data? JSON

JSON is a different way of expressing the data. Lets take the example of object Apple.
The Apple is a fruit red in color.

Fruit named Apple
In computer language, we can express that as

var fruit;
fruit="apple";

For additional details, JSON comes to the rescue where color description can be given.

fruits="{'Name':'Apple','Color':'Red'}"

In Powershell, we can read JSON easily using ConvertTo and ConvertFrom Json function.PowerShell is very simple compared to other programming languages. One line of code!

Below is a script that converts the fruits JSON and displays that in beautiful table format.
$fruits="{'Name':'Apple','Color':'Red'}","{'Name':'Mango','Color':'Yellow'}"
$fruits |ConvertFrom-Json

In real world, I heavily use SharePoint and there are times when the JSON results are not converted sometimes. In that case, I have to do minor tweaks to display the JSON data in powershell. Below is a code that reads REST results from SharePoint, but the tabular data is not displayed.
$listName="PSRestList"
$restUrl="/_api/web/lists/GetByTitle('"+$listName+"')/items"
$listItems=Read-SPObject -targetSite $targetSite -User $User -restUrl $restUrl
$listItems

How to handle the error? By replacing the conflicting columns with another column.
#ID error
$results = $listItems.ToString().Replace("ID", "_ID") | ConvertFrom-Json
$results.d.results|select Title



No comments:

Post a Comment