Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 840 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I correctly convert a HashTable to JSON in PowerShell?

#1
I'm using PowerShell to send a `POST` request to a `REST API`. The body of the request looks like this:

{
"title": "game result",
"attachments": [{
"image_url": "http://contoso/",
"title": "good work!"
},
{
"fields": [{
"title": "score",
"value": "100"
},
{
"title": "bonus",
"value": "50"
}
]
}
]
}

Now, the following PowerShell script produces the wrong output:

$fields = @(@{title='score'; value='100'},@{title='bonus'; value='10'})
$fieldsWrap = @{fields=$fields}
#$fieldsWrap | ConvertTo-Json
$attachments = @(@{title='good work!';image_url='http://contoso'},$fieldsWrap)
$body = @{title='game results';attachments=$attachments}
$json = $body | ConvertTo-Json
$json

Line 3 (if uncommented) produces the correct output, however line 7 produces:

{
"attachments": [{
"image_url": "http://contoso",
"title": "good work!"
},
{
"fields": "System.Collections.Hashtable System.Collections.Hashtable"
}
],
"title": "game result"
}

It obviously writes out the type name of the `HashTable`, which is the default `ToString()` implementation I assume.
How do I get the correct output?
Reply

#2
This gives the JSON output you want:

@{
title = "game result"
attachments = @(
@{
image_url = "http://contoso/"
title = "good work!"
},
@{
fields = @(
@{
title = "score"
value = "100"
},
@{
title = "bonus"
value = "50"
}
)
}
)
} | ConvertTo-Json -Depth 4

Wouldn't have worked without Martin Brandl's advice, though :)
Reply

#3
The [ConvertTo-Json][1] cmdlet has a `-depth` parameter which:

> Specifies how many levels of contained objects are included in the
> JSON representation. The default value is 2.

Thus, you have to increase it:

$body | ConvertTo-Json -Depth 4



[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through