【问题标题】:How to add a value and key into existing JSON file over powershell?如何通过powershell将值和键添加到现有的JSON文件中?
【发布时间】:2020-12-31 09:55:59
【问题描述】:

我想在我现有的JSON 文件中添加一个带有值的附加键。不幸的是我做不到。这里有一个简短的概述:

我在运行 powershell 脚本之前的 JSON 文件:

[
  {
    "id": "1",
    "description": [
      {
        "country": "Brazil"
      },
      {
        "country": "Mexico"
      }
    ]
  },
  {
    "id": "2",
    "description": [
      {
        "country": "Argentina"
      }
    ]
  }
]

我的愿望是,在我的 powershell 脚本运行后 JSON 文件应该是什么样子:

[
  {
    "id": "1",
    "description": [
      {
        "country": "Brazil",
        "city": "Rio de Janeiro"
      },
      {
        "country": "Mexico",
        "city": "Mexico City"
      }
    ]
  },
  {
    "id": "2",
    "description": [
      {
        "country": "Argentina",
        "city": "Buenos Aires"
      }
    ]
  }
]

我的 powershell 脚本:

function GetCity($country) {
    $x = "not available"                
    If ( $country -eq "Brazil" ) { $x = "Rio de Janeiro" }
    If ( $country -eq "Mexico" ) { $x = "Mexico City" }
    If ( $country -eq "Argentina" ) { $x = "Buenos Aires" }    
    return $x    
}

# Source the JSON content
$jsonFile = 'C:\Temp\test.json'
$jsonContent  = Get-Content -Path $jsonFile

# Convert JSON to PSObjects
$jsonAsPsObjects = $jsonContent | ConvertFrom-Json

foreach ($info in $jsonAsPsObjects) {
    $result = GetCity($info.description.country)
    jsonContent | Add-Member -Type NoteProperty -Name "City" -Value $result
}

# Save JSON back to file
$json | ConvertTo-Json | Set-Content $jsonFile

错误:

jsonContent : 术语“jsonContent”未被识别为 cmdlet、函数、脚本文件或可运行的程序。检查 名称的拼写,或者如果包含路径,请验证路径 是正确的,然后再试一次。

我该如何解决这个问题?

【问题讨论】:

  • 顺便说一句:必须调用 PowerShell 函数、cmdlet、脚本和外部程序方法 - foo('arg1', 'arg2')。如果您使用, 分隔参数,您将构造一个命令将其视为单个参数数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2 或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。

标签: json powershell powershell-5.0


【解决方案1】:

有两个问题:

  • jsonContent 在声明 jsonContent | Add-Member ... 中应该是 $jsonContent

  • 您忽略了循环遍历 description 属性的数组元素,每个要添加一个 city 属性。

我建议将您的代码简化如下:

function Get-City {
  param([string] $country)
  # Use a `switch` statement:
  switch ($country) {
    'Brazil' { return 'Rio de Janeiro' }
    'Mexico' { return 'Mexico City' }
    'Argentina' { return 'Buenos Aires' }
    default { return 'not available' }
  }
}

$jsonFile = 'C:\Temp\test.json'

(Get-Content -Raw $jsonFile | ConvertFrom-Json) | ForEach-Object {
  # Add a 'city' property to each object in the 'description' property.
  $_.description.ForEach({ 
    Add-Member -InputObject $_ city (Get-City $_.country) 
  })
  $_  # output the modified object
} | ConvertTo-Json -Depth 3  # | Set-Content $jsonFile

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 2020-04-26
    • 2017-10-17
    • 2020-07-20
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多