首页 > 解决方案 > PowerShell ConvertFrom-Json 未将 JSON 列表转换为 Json 对象

问题描述

我有一个 json 输出作为列表,我想使用 PowerShell 在 tags 参数中添加一个属性

$json = @'
[
    {
       "tags": [],
        "name": "[concat(parameters('factoryName'), '/Veh_Obj')]",
        "properties": {
            "type": "AzureDataLakeStoreFile",
        }
    }
]
'@
#$json = 'C:\workspace\cucumber_report.29776.json'

$obj = $json | ConvertFrom-Json 

# Append new objects to the array.
$obj.tags += [pscustomobject] @{ name = 'newname1' }

# Convert back to JSON.
$obj | ConvertTo-Json -Depth 10 | Set-Content $json

但我收到如下错误 在此对象上找不到属性“标签”。验证该属性是否存在并且可以设置。 看起来只有当我传递 JSON 列表时才会出现问题,使用正常的 json 输入,这工作正常

标签: jsonpowershell

解决方案


  1. 行中的尾随逗号"type": "AzureDataLakeStoreFile",导致错误ConvertFrom-Json : Invalid JSON primitive
  2. $obj.GetType().Name返回Object[](注意原始的最顶层元素json是一个数组[])。

利用

$obj[0].tags += [pscustomobject] @{ name = 'newname1' }

推荐阅读