【问题标题】:Powershell json formatPowershell json 格式
【发布时间】:2018-04-02 17:34:09
【问题描述】:

我有一个关于使用 powershell 从/到 json 转换的问题。我需要一个具有特定格式的 json(用于 REST 调用),但如果我执行 convertfrom-json 和 convertto-json 格式错误,我不知道如何更改它。 这是原始格式:

{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  [1522678260000],
                                 "values":  ["compliant"],
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

如果我做一个 converfrom-json ...然后我改变一些值然后我做一个 convertto-json 格式是没有括号的:

{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  "1522678260000",
                                 "values":  "compliant",
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

谢谢!

【问题讨论】:

  • 我没有对 json 做很多工作,但我怀疑您需要在 json 中更改新值之前将其强制为数组。
  • 方括号表示该值是一个数组。如果 powershell 不将输入解释为数组,则它不会输出带有方括号的 json 文本。一般没关系,你的api有抱怨吗?
  • 如果再深入一点,你会注意到单值数组不只是变成了一个值,而且值本身."property-content"."timestamps" 类型也从int64 转换为string...

标签: json rest powershell


【解决方案1】:

数组被ConvertTo-Json cmdlet 展平,因为-Depth 参数默认设置为2。如果您提高-Depth,它将解决您的问题:

PS C:\> $a = ConvertFrom-JSON @'
>> {
>>     "property-content":  [
>>                              {
>>                                  "statKey":  "Test|Test1",
>>                                  "timestamps":  [1522678260000],
>>                                  "values":  ["compliant"],
>>                                  "others":  "",
>>                                  "otherAttributes":  ""
>>                              }
>>                          ]
>> }
>> '@
PS C:\> $a | convertTo-JSON -Depth 5
{
    "property-content":  [
                             {
                                 "statKey":  "Test|Test1",
                                 "timestamps":  [
                                                    1522678260000
                                                ],
                                 "values":  [
                                                "compliant"
                                            ],
                                 "others":  "",
                                 "otherAttributes":  ""
                             }
                         ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多