目前,我正在尝试调用API以JSON数据为主体来运行POST。因此,我想知道是否有人可以告诉我如何设置变量$postParams
中下面的文本的格式。我在使用JSON方面很陌生,因此遇到了很多麻烦。
目前,我只有以下内容,不知道该如何处理第二行。
$postParams = @{name='Example'}
这是我希望添加到$ postParams中的全部数据。因此,如果您能在第二,第四和第八方面帮助我,那就太好了。谢谢!
{
"name":"Example",
"template":{"name":"Template"},
"url":"http://localhost",
"page":{"name":"Landing Page"},
"smtp":{"name":"Sending Profile"},
"launch_date":"2019-10-08T17:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"test group"}]
}
最佳答案
您需要一个here-string和ConvertFrom-Json。
here-string:
Quotation marks are also used to create a here-string. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks.
结果代码:
# Use a PowerShell here string to take JSON as it is
$jsonString = @"
{
"name":"Example",
"template":{"name":"Template"},
"url":"http://localhost",
"page":{"name":"Landing Page"},
"smtp":{"name":"Sending Profile"},
"launch_date":"2019-10-08T17:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"test group"}]
}
"@
# Pipe the string to create a new JSON object
$jsonObject = $jsonString | ConvertFrom-Json
# The resulting JSON object has properties matching the properties in the orig. JSON
$jsonObject.name
$jsonObject.url
# Nested property
$jsonObject.template.name
# Nested property in array
$jsonObject.groups[0].name
我已经在tio.run上发布了上述代码的在线版本,因此您可以试用它。如果要更新
$jsonObject
的多个属性,可以执行以下操作: $jsonObject.name = "NEW NAME"
$jsonObject.url = "NEW URL"
$jsonObject | ConvertTo-Json
ConvertTo-Json将获取您的对象并创建适当的JSON字符串:{
"name": "NEW NAME",
"template": {
"name": "Template"
},
"url": "NEW URL",
"page": {
"name": "Landing Page"
},
"smtp": {
"name": "Sending Profile"
},
"launch_date": "2019-10-08T17:20:00+00:00",
"send_by_date": null,
"groups": [
{
"name": "test group"
}
]
}
如果$jsonObject
的深度超过两个级别,请使用-Depth
参数,否则,并非所有对象信息都将包含在JSON字符串中。ConvertTo-Json:
-Depth
Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.
这是tio.run link到
ConvertTo-Json
的示例。希望能有所帮助。
关于json - 在Powershell中输入JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154027/