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":"[email protected]" },
    { "username":"morgan", "email":"[email protected]" },
    { "username":"smith", "email":"[email protected]" }
]}'

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
-------- -----
kevin    [email protected]
morgan   [email protected]
smith    [email protected]

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


Advertisement

Leave a Comment