- Create a certificate-signed RDP shortcut via Group Policy - Fri, Aug 9 2019
- Monitor web server uptime with a PowerShell script - Tue, Aug 6 2019
- How to build a PowerShell inventory script for Windows Servers - Fri, Aug 2 2019
In today's world, application programming interfaces (APIs) are everywhere. APIs give developers the ability to communicate with a software service through code, typically over HTTP/HTTPS. To ensure this communication maintains some standard, many APIs use JSON.
Along with its use in APIs, JSON is also just an excellent way to store structured data. Similar to XML in a way, JSON is a way to represent collections of hierarchical objects. Lucky for us, PowerShell can work with JSON right out of the box through a couple of different commands.
A simple JSON example
Of course, you can also manage JSON in PowerShell. Let's start by using an example JSON string representing multiple employees.
$employeesJson = '{"employees":[ { "firstName":"John", "lastName":"Doe" }, { "firstName":"Anna", "lastName":"Smith" }, { "firstName":"Peter", "lastName":"Jones" } ]}'
The sample JSON above might be a string returned from an API, for instance. I assign this JSON string to the $employeesJson variable. When I return this variable to the console, you can see that it's just a simple string.
ConvertFrom-Json
At this point, I can't quickly pull individual employees out of here or perhaps query this entire set for employees with a particular last name. I need to convert this to a structured format using ConvertFrom-Json. To do that, I provide the JSON string as the value of the InputObject parameter.
$employeesObject = ConvertFrom-Json –InputObject $employeesJson
Now you can see below that I have an object I can work with. At this point, I can reference any properties like I usually would in this object. I use dot notation and query properties like I can with any other PowerShell object. I can now more easily find all employees:
PS> $employeesObject.employees firstName lastName --------- -------- John Doe Anna Smith Peter Jones
Notice that $employeesObject.employees is an array. PowerShell understands that all employees were part of a collection, and the ConvertFrom-Json command converted it to a PowerShell array. This is handy when you've got complicated JSON strings.
The ConvertFrom-Json cmdlet will read all the JSON attributes. It will understand whether each is part of a collection or not and will create the appropriate object type.
Maybe I want to find all employees with the first name of 'John.' No problem. This wouldn't have been possible as a string.
PS> $employeesObject.employees | where {$_.firstName -eq 'John'} firstName lastName --------- -------- John Doe
ConvertTo-Json
But what if you already have an object you want to convert to a JSON string? In that case, you'd use ConvertTo-Json. Let's take our freshly converted object as an example and convert it back to the JSON string we started out with. Doing so just involves either using the InputObject parameter or using the PowerShell pipeline and passing the object directly to the ConvertTo-Json command.
Subscribe to 4sysops newsletter!
PS> $backtoJson = $employeesObject | ConvertTo-Json PS> $backtoJson { "employees": [ { "firstName": "John", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] } PS> $backtoJson | Get-Member TypeName: System.String
You can now see that we're back to a JSON string. But now it doesn't look exactly like our original JSON string because PowerShell will attempt to insert carriage returns inside of the string to make it more readable.
Thanks for the info about $jsonresultvariable | get-member trick. Now I can work with json output in a normal way.
Is there any way to preserve a single quote using ConvertTo-JSON? I have yet to figure out a way to do this..
David F.
@figueroa2david
It’s a bit late but just noticed your question…
Single quotes are used in PowerShell to avoid the expansion of variables during the moment a string is assigned or used. After that moment, there is no persistence of single or double quotes.
However, despite it seams to be interpreted correctly by PowerShell, the single quote has no meaning in JSON.
Here is the official JSON semantic:
https://www.json.org/
After Converting from JSON my data looks like this :
userName : gregk@thespicergroup.ca
firstName : Joanna
lastName : Carson Skead
role :
accountNumbers : {CAJ0000212, CAJ0000208}
How do i retreive multiple accountNumbers into 1 variable ?
@Sri
This is related to the application or language which is using the JSON data.
I guess you are using Java…
@Luc Fullenwarth
I’m using powershell to read the data in variables
@Sri
Sorry I’ve read it the wrong way (convert to JSON instead of reading convert from JSON).
I need glasses… 😀
To access the data inside accountNumbers you must first determine the type (hashtable or array).
Assuming your data is stored in a variable named $User
If the data is an array you can access it by the element number
If the data is a hashtable you can access it by the element name
In any cases you can enumerate the data with the foreach statement
@Luc Fullenwarth
Thank you , that helps alot f0r me
I was using this but the values are not getting comma separated
$acc=$user.accountNumbers
for ($i=0; $i-le$acc.Count; $i++)
{
$a+=@($acc[$i]) -join”,”
}
@sri
You must first build the array and then only you can join members. You cannot do both at the same time.
Furthermore, you should use Less than (lt) instead of Less or equal then (le). Otherwise you will get an empty value at the end.
Here is a proposition of code.
$acc=$user.accountNumbers
for ($i=0; $i-lt $acc.Count; $i++)
{
$a += @($acc[$i])
}
$b = $a -join ‘,’
I need to update the Json file value as true for speific key by using power shell in existing file