json - 在Powershell中输入JSON数据

标签 json powershell api

目前,我正在尝试调用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-stringConvertFrom-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 linkConvertTo-Json的示例。
希望能有所帮助。

关于json - 在Powershell中输入JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57154027/

相关文章:

javascript - 在 PHP 本身中将 PHP 数组转换为 JS 数组

json - 如何使用 Rust 中的现有模式文件验证 JSON?

powershell - 远程更改Windows服务上的帐户名和密码

api - 如何将字符串转换为 time.Time

javascript - D3 图表 - 圆环图 SVG 中心的图像

c# - 将 Json 反序列化为 NJsonSchema 生成的对象,其中枚举包含空格

powershell - 是否可以被动安装 .EXE 但仍使用 Powershell 显示 GUI?

regex - 如何使用正则表达式重命名Powershell中的文件?

javascript - Instagram API 重定向 uri

java - 尝试使用 Java 向 Reddit 发表评论