Thursday, 7 June 2018

Powershel : Convert JSON String to PS Object and Vice-versa

Many software services moving towards cloud environment and providing APIs to communicate with service. To standardize this communication many software APIs use JSON format to receive and return data. In this post, I am going to share powershell script to convert json to object and convert object to json string.

Convert JSON content to PS Object :

You can easily convert json text into object using the powershell cmdlet ConvertFrom-Json. Consider the below sample JSON that might be a HTTP/HTTPS response content returned from some API.
$usersJson = '{"users":[
    { "username":"kevin", "email":"" },
    { "username":"morgan", "email":"" },
    { "username":"smith", "email":"" }
Run the following command to convert the above json string to ps object.
$usersObject = ConvertFrom-Json –InputObject $usersJson
Now you can easily list the ps object properties
PS C:\> $usersObject.users

username email
-------- -----

Convert PS Object to JSON String :

You can convert the above ps object into json text using the powershell cmdlet ConvertTo-Json.
$newUsersJson = $usersObject | ConvertTo-Json

parse json string as ps object and convert ps object to json string


No comments:

Post a Comment