Powershell:读取嵌套 json

Powershell: reading nested json

我正在尝试根据外部 json 文件在我的数据块集群上安装库。

文件构造如下:

{"libraries":[

    {
      "pypi": {
        "package": "sparkmeasure==0.14.0"
      }
    },
    {
      "maven": {
        "coordinates": "azureml-core==1.20.0"
      }
    }
]
}

然后我尝试读取文件、构建请求主体并调用其余方法。

$json = Get-Content $filePath| Out-String | ConvertFrom-Json -Depth 99 

$Region = $Region.Replace(" ", "")

$uri = "https://$Region.azuredatabricks.net/api/2.0/libraries/install"

$Body = @{ "cluster_id" = $ClusterId }

$Body['libraries'] = $json.libraries
$BodyText = $Body | ConvertTo-Json
Write-Output $BodyText 

Invoke-RestMethod -Uri $uri -Body $BodyText -Method 'POST' -Headers @{ Authorization = $InternalBearerToken }

这是我得到的输出正文:

{
  "libraries": [
    {
      "pypi": "@{package=sparkmeasure==0.14.0}"
    },
    {
      "maven": "@{coordinates=azureml-core==1.20.0}"
    }
  ],
  "cluster_id": "myclusterid"
}

但是,我只需要从文件中获取值,所以我的预期结果是这样的:

{
  "libraries": [
    
        {
          "pypi": {
            "package": "sparkmeasure==0.14.0"
          }
        },
        {
          "maven": {
            "coordinates": "azureml-core==1.20.0"
          }
        }
    ],
  "cluster_id": "myclusterid"
}

我是 PowerShell 的新手,所以我想知道是否有一些简单的方法可以保留 json 文件的结构,而不是将那些嵌套结构作为数组?

在这种情况下,您可以使用如下输出中的简单替换:

我只是在使用你的输出然后将其向前推进

$a = @'
{
  "libraries": [
    {
      "pypi": "@{package=sparkmeasure==0.14.0}"
    },
    {
      "maven": "@{coordinates=azureml-core==1.20.0}"
    }
  ],
  "cluster_id": "myclusterid"
}
'@
($a.Replace('@{','')).replace('}"','"')   #This is what will replace the things as per your need.

此外,在转换为 JSON 时,只需添加 -Depth,如 Jeroen

所示