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":"kevin@test.com" },
{ "username":"morgan", "email":"morgan@test.com" },
{ "username":"smith", "email":"smith@test.com" }
]}'
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 kevin@test.com
morgan morgan@test.com
smith smith@test.com
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
No comments:
Post a Comment