创建 JSON 字符串、PowerShell 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44597175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a JSON string, PowerShell object
提问by Sudheej
I am unable to create a variable on this request so I can later convert the variable to JSON using converttojson
我无法在此请求上创建变量,因此我稍后可以使用 converttojson 将该变量转换为 JSON
{
"update": {
"comment": [
{
"add": {
"body": "Comment added when resolving issue"
}
}
]
},
"transition": {
"id": "21"
}
}
Tried the below
尝试了以下
$jsonRequest = @{
update= @{
comment =@{
add =@{
body = "$Description"
}
}
}
transition =@{
id = $TransactionID
}
}
But get an output as below
但得到如下输出
{
"transition": {
"id": 1
},
"update": {
"comment": {
"add": "System.Collections.Hashtable"
}
}
}
回答by TessellatingHeckler
Comment" in your JSON is a list containing a hashtable, in your code it's a hashtable containing a hashtable.
JSON 中的 Comment" 是一个包含哈希表的列表,在您的代码中它是一个包含哈希表的哈希表。
This looks right by making it an array of one item:
通过使其成为一个项目的数组,这看起来是正确的:
$jsonRequest = [ordered]@{
update= @{
comment = @(
@{
add =@{
body = "$Description"
}
}
)
}
transition = @{
id = 21
}
}
$jsonRequest | ConvertTo-Json -Depth 10
And I've made it '[ordered]' so the update and transition come out in the same order as your code, although that shouldn't really matter.
我已经将它设为“[ordered]”,因此更新和转换的顺序与您的代码相同,尽管这并不重要。

