PowerShell creating JSON objects

For a single level object, I find this to work well (and it’s simple/easy to understand):

$Body = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Body.Add('searchString', $Search)
$JsonBody = ConvertTo-Json $Body

More lines can be added with the $Body.Add function. Also, both arguments can take a string with single quote marks; I happened to be using a variable in that example.
This creates a JSON object that looks like this:

"searchString": ""

Like I said, very simple. The indents don’t show up here, but you can see them in the PS console.

For multiple level or nested JSON, this is the only way I can find that works. It’s a bit less “clean” in my opinion, since it’s not using native PowerShell functions and objects, but it does the job.

$JsonBody = ConvertTo-Json -Depth 2 @{"contact" = @{"firstName" = $firstName; "lastName" = $lastName; "email" = $email}; "type" = "User"}

That gives you an object which looks like this:

"contact": {
"email": "dfsgklj@dfgsd.com",
"firstName": "JPake",
"lastName": "GBgfhmio"
"type": "User"

Then you can fire that off somewhere using Invoke-WebRequest or whatever suits your needs.

Comments are closed.

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: