将 JSON 属性更改为数组(如果不是数组电源外壳)



我有一个 JSON,我想检查它是否是一个数组,如果不是,我想更新 JSON 并将其更改为数组

{
"Customer": [{
"id": "123"
}],
"address": {
"type": "home",
"name": "what",
"description": "",
"adi:water": {
"type": "comp",
"location": "grass"
},
"att": [
{
"name": "cat",
"type": "int"
},
{
"name": "ds",
"type": "string"
}
]
}
}
#For example address is not an array, I want to change so address is an array of one single object

到目前为止的代码

$File = ((Get-Content -Encoding UTF8 -path Test.json -Raw)
$File = $File| ConvertFrom-Json
$File.address = $File.address | Select-Object * -ExcludeProperty streets #This line changes it to an object instead of an array

我希望地址是一个数组。我可以在Powershell中做到这一点吗?

使用ForEach-Object并通过将其包含在@(...)中来重新分配address属性值,数组子表达式运算符,以确保它是一个数组(如果它已经是一个数组,则没有任何变化[1]):

@'
{
"Customer": [
{
"id": "123"
}
],
"address": {
"type": "home",
"name": "what",
"description": "",
"adi:water": {
"type": "comp",
"location": "grass"
},
"att": [
{
"name": "cat",
"type": "int"
},
{
"name": "ds",
"type": "string"
}
]
}
}
'@ | ConvertFrom-Json | 
ForEach-Object { 
$_.address = @($_.address | Select-Object * -ExcludeProperty streets)
$_ 
} |
ConvertTo-Json -Depth 4

请注意赋值后的独立$_语句:它使用 PowerShell 的隐式输出功能确保(修改后的)输入对象也输出(到下一个管道段) - 请参阅此答案。

注意默认情况下,ConvertTo-Json将序列化深度限制为2,因此上面使用了-Depth 4以防止数据丢失。一般来说,请记住,你可能必须传递一个-Depth参数来ConvertTo-Json防止数据丢失- 见这篇文章[2]。

上面生成以下内容,显示address属性现在是一个数组:

{
"Customer": [
{
"id": "123"
}
],
"address": [
{
"type": "home",
"name": "what",
"description": "",
"adi:water": {
"type": "comp",
"location": "grass"
},
"att": [
{
"name": "cat",
"type": "int"
},
{
"name": "ds",
"type": "string"
}
]
}
]
}

[1] 从技术上讲,会创建一个现有数组的(浅)副本,但这在这里没有任何区别.
要了解有关@()运算符的更多信息,请参阅此答案。

[2] 此要求很麻烦且容易错过,但为了向后兼容而没有更改。但是,PowerShell 版本 7.1 至少会在(可能是默认值)-Depth值不足时发出警告:请参阅 GitHub 问题 #8393.
中的此 PR 和相关讨论此外,在将 JSON cmdlet 的实现从 Newtonsoft.Json 库移动到新的内置System.Text.JsonAPI 的上下文中,可能会重新审视该问题。 在 v7.1 之后的某个时候,这将不可避免地需要进行重大更改 - 请参阅此 PR。

相关内容

最新更新