【问题标题】:How to enter press square brackets in PowerShell on JSON File如何在 JSON 文件的 PowerShell 中输入方括号
【发布时间】:2019-08-27 09:29:51
【问题描述】:

如何使用 PowerShell 查询 JSON 文件中“类型”字符串的更改值?我无法进入“类型”字符串。

JSON 文件

{
"name":  "b",
"compatibilityLevel":  1400,
"model":  {
              "culture":  "c",
              "dataSources":[
                                  {
                                      "type":  "structured"
                                  }
                            ]
         }}

PowerShell

$pathToJson =  "C:\Model.bim"

$a = Get-Content $pathToJson | ConvertFrom-Json

$a.'model.dataSources.type' = "c"

$a | ConvertTo-Json -Depth 10  | Set-Content $pathToJson

【问题讨论】:

  • $a.model.dataSources = ,@{type = 'C'}

标签: arrays json powershell member-enumeration


【解决方案1】:

tl;dr

$a.model.dataSources[0].type = 'c'

注意需要指定索引[0],因为$a.model.dataSources是一个数组


对于你尝试了什么

$a.'model.dataSources.type' = "c"

  • 您不能使用存储在 string ('...') 中的属性 path 直接访问嵌套属性,因为 PowerShell 将 'model.dataSources.type' 解释为单个属性。

  • 即使解决了这个问题,$a.model.dataSources.type = "c" 也不会 起作用,因为$a.model.dataSources 返回值的数组,而您不能直接设置 em> 该数组的 elements 上的属性;相反,您必须明确定位感兴趣的数组元素,如上所示 ([0])。

    • 请注意,您可以通过名为 member enumeration 的 PSv+ 功能获取数组元素的 .type 值和 $a.model.dataSources.type,但这在设置中不起作用> - 通过设计,防止可能无意更新具有相同值的所有数组元素;见this answer

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多