我有一个对象需要扩展.问题是在转换为JSON后,内部数组对象始终为空.我不明白我的失败在哪里

$settings = @{}

# create the nested object
$settings | Add-Member -Type NoteProperty -Name nested_obj -Value @{}

# extend the nested object with an array property
$settings.nested_obj | Add-Member -Type NoteProperty -Name nested_property -Value @( "1", "2" )

# {"nested_property":["1","2"]}
Write-Host ( $settings.nested_obj | ConvertTo-Json -Compress -Depth 100 )

# {"nested_obj":{}} - the nested object is unexpectedly empty
Write-Host ( $settings | ConvertTo-Json -Compress -Depth 100 )

谢谢

推荐答案

ConvertTo-Json发现存储在$settings中的对象是hashtable,因此它开始序列化字典条目,而不是序列化属性--您没有任何字典条目.

nested_objnested_property值作为字典条目附加:

# create root hashtable/dictionary
$settings = @{}

# create the nested hashtable
$settings['nested_obj'] = @{}

# add an entry to the nested hashtable
$settings['nested_obj']['nested_property'] = @( "1", "2" )

# {"nested_obj":{"nested_property":["1","2"]}}
Write-Host ( $settings | ConvertTo-Json -Compress -Depth 100 )

...或者,使用实际的(非字典)对象

# create object hierarchy
$settings = [PSCustomObject]@{
  nested_obj = [PSCustomObject]@{
    nested_property = @( "1", "2" )
  }
}

# {"nested_obj":{"nested_property":["1","2"]}}
Write-Host ( $settings | ConvertTo-Json -Compress -Depth 100 )

PowerShell2.0的类似功能使用Add-Member,与您最初的try 非常相似,不同之处在于我们将@{}替换为New-Object psobject:

$settings = New-Object psobject
$settings | Add-Member -Type NoteProperty -Name nested_obj -Value (New-Object psobject)
$settings.nested_obj | Add-Member -Type NoteProperty -Name nested_property -Value @( "1", "2" )

# {"nested_obj":{"nested_property":["1","2"]}}
Write-Host ( $settings | ConvertTo-Json -Compress -Depth 100 )

Json相关问答推荐

JOLT拉平数组

从json数组中删除特定元素

使用更高级别架构中的字段值在$def内实现约束

如何判断响应数组是否存在以及S是否有其他内容...?

在 python 中循环 JSON 数组

未知的META规范,无法验证.[规范v1.0.1]

Delphi 11.3无法从变体创建/添加JSON

使用不同行数的数据创建嵌套Jolt

如何在 terraform 输出中打印一组用户信息

JOLT 转换仅过滤一个字段

我需要在 mongodb compass 中检索索引(编号 1)信息

将 json 文件转换为 json 对象会打乱对象的顺序

Powershell 无法从名为 count 的键中获取价值

如何限制resolveJsonModule的范围?

在PowerShell中按时间戳过滤JSON

为什么我不能在 C# 中引用 System.Runtime.Serialization.Json

了解 JSON Schema 草稿版本 4 中的additionalProperties关键字

ASP.NET MVC:使用 JsonResult 控制属性名称的序列化

如何在 Django JSONField 数据上聚合(最小/最大等)?

无法将空值放入 JSON 对象