簡體   English   中英

如何通過 powershell 將值和鍵添加到現有的 JSON 文件中?

[英]How to add a value and key into existing JSON file over powershell?

我想在我現有的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、function、腳本文件或可運行程序的名稱。 檢查名稱的拼寫,或者如果包含路徑,請驗證路徑是否正確並重試。

我該如何解決這個問題?

有兩個問題:

  • jsonContent應該是語句 jsonContent 中的$jsonContent jsonContent | Add-Member... jsonContent | Add-Member...

  • 您忽略了遍歷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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM