【问题标题】:Manipulate JSON File with multiple objects using Powershell使用 Powershell 处理包含多个对象的 JSON 文件
【发布时间】:2020-09-02 00:30:07
【问题描述】:

我有一个名为 index.json 的 JSON 文件,如下所示:

{ 
  "First": {
    "href": "test/one two three.html",
    "title": "title one"
  },

  "Second": {
    "href": "test/test test/one two three four.html",
    "title": "title two"
    
  }
}

我想写一个powershell脚本来更新每个对象的href,用-替换空格。

JSON 文件应如下所示:

{ 
  "First": {
    "href": "test/one-two-three.html",
    "title": "title one"
  },

  "Second": {
    "href": "test/test-test/one-two-three-four.html",
    "title": "title two"
    
  }
}

我从这篇文章中得到了一些帮助: Iterating through a JSON file PowerShell

我已经编写了一个脚本来获取所有的 href 值,我不知道如何在原始 JSON 文件中更新相同的值。我的脚本如下所示:

function Get-ObjectMembers {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$True)]
        [PSCustomObject]$obj
    )
    $obj | Get-Member -MemberType NoteProperty | ForEach-Object {
        $key = $_.Name

        [PSCustomObject]@{Key = $key; Value = $obj."$key"}
    }
}

$a = Get-Content 'index.json' -raw | ConvertFrom-Json | Get-ObjectMembers 


foreach($i in $a){
$i.Value.href.Replace(" ","-")
} 

【问题讨论】:

    标签: json powershell


    【解决方案1】:

    我是这样做的。

    $path='index.json'
    $Content= (Get-Content $path -raw | ConvertFrom-Json)
    $memberNames=( $Content | Get-Member -MemberType NoteProperty).Name
    foreach($memberName in $memberNames){
        ($Content.$memberName.href)=($Content.$memberName.href).Replace(" ","-")
        }
    $Content | ConvertTo-Json | Out-File $path -Append
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-12
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多