【问题标题】:Find and Replace all instances of a value in JSON with different value in Powershell在 Powershell 中用不同的值查找并替换 JSON 中值的所有实例
【发布时间】:2021-01-17 07:54:40
【问题描述】:

我有一个较大的 JSON 值,需要用其他值替换。基本上我正在尝试在powershell中查找和替换所有内容。我想删除我们看到 Rock to Rocky 的地方

JSON

{
  "Customer": [
    {
      "id": "123"
    }
  ],
  "Nationality": [
    {
      "name": "US",
      "id": "456"
    }
  ],
  "address": [
    {
      "$type": "Home",
      "name": "Houston",
      "streets": [
        {
          "name": "Union",
          "postalCode": "10",
        }
      ]
    },
    {
      "$type": "Office",
      "name": "Hawai",
      "streets": [
        {
          "name": "Rock",
          "postalCode": "11",
        }
      ]
    },
    {
      "$type": "Office1",
      "name": "Hawaii",
      "streets": [
        {
          "name": "Rock 678",
          "postalCode": "11",
        }
      ]
    },
    {
      "$type": "Office2",
      "name": "Hawai2",
      "streets": [
        {
          "name": "Rock",
          "postalCode": "11",
        }
      ]
    }
    
  ]
}

我正在将 JSON 更改为对象,但不确定如何查找和替换所有内容。我想删除我们看到 Rock to Rocky 的地方

代码

$FileContent = Get-Content -Path "Test.json" -Raw | ConvertFrom-Json
$FileContent.address.streets.name = 'Rocky' // I want to do for all the instances.

$FileContent | ConvertTo-Json -Depth 100 | Out-File "Test.json" -Force

【问题讨论】:

  • (Get-Content -path C:\Users\Username\Folder\File.json -Raw) -replace 'Rock' , 'Rocky' |设置内容-路径 C:\Users\Username\Folder\File.json;

标签: json powershell powershell-core


【解决方案1】:

如何使用 Powershell 替换文件中的字符串值?

  • 将“摇滚”替换为“洛基”;

  • 设置文件中的内容。

    (Get-Content -path C:\Users\Username\Folder\File.json -Raw) -replace 'Rock' , 'Rocky' | Set-Content -path C:\Users\Username\Folder\File.json;
    

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 2017-01-30
    • 2022-11-17
    • 2019-03-18
    • 1970-01-01
    • 2018-08-16
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多