【问题标题】:How to read a JSON file and rearrange the code如何读取 JSON 文件并重新排列代码
【发布时间】:2019-06-20 03:41:27
【问题描述】:

我想读取我的 JSON 文件并使用重新排列的代码编写相同的文件。 我的 JSON 文件给了我类似的东西:

{
  "one": [
    {
      "name": { "displayName": "Alex" },
      "two": [
        {
          "date": "20072008",
          "data": {
            "id": "524556",
            "fullname": "Alexandre Gagne",
            "name": "Alexandre",
            "lastName": "Gagne"
          }
        }
      ]
    }
  ]
}

但我想要这样的东西

{
  "id": "524556",
  "fullname": "Alexandre Gagne",
  "name": "Alexandre",
  "lastName": "Gagne"
}

这是我使用的代码:

$jsonfile118 = 'C:/Users/Web_Q/Desktop/json/8472382-2017-2018.json'
$json118 = Get-Content $jsonfile118 | Out-String | ConvertFrom-Json
$json118.stats.splits
$json118 | Add-Member -Type NoteProperty -Name "id" -Value 524556
$json118 | ConvertTo-Json -Depth 10 | Set-Content $jsonfile118

我还使用了另一段代码,它给了我我想要的东西,但只在终端中,当我使用 Set-Content 时,输出如下所示:

"{ \'id'\ 536453 }"

代码如下:

(New-Object PSObject |
    Add-Member -PassThru NoteProperty id $json118.stats.splits.getId
) | ConvertTo-Json

【问题讨论】:

  • 您的输入数据与您的代码和假定的输出不匹配。

标签: json powershell


【解决方案1】:

你需要的是,

  • 将 Json 转换为对象

  • 选择需要的成员

  • 转回json

    $Data = $JsonString | ConvertFrom-Json
    
    $Data.One.Two.Data | ConvertTo-Json
    

【讨论】:

  • 请注意,这只是偶然的,因为 onetwo 两个数组都只有一个元素。
【解决方案2】:

使用这个Flatten-Object cmdlet

@'
{
  "one": [
    {
      "name": { "displayName": "Alex" },
      "two": [
        {
          "date": "20072008",
          "data": {
            "id": "524556",
            "fullname": "Alexandre Gagne",
            "name": "Alexandre",
            "lastName": "Gagne"
          }
        }
      ]
    }
  ]
}
'@ | ConvertFrom-Json | Flatten-Object -Depth 9 -Base "" | ConvertTo-Json

结果:

{
    "one.name.displayName":  "Alex",
    "one.two.date":  "20072008",
    "one.two.data.id":  "524556",
    "one.two.data.fullname":  "Alexandre Gagne",
    "one.two.data.name":  "Alexandre",
    "one.two.data.lastName":  "Gagne"
}

它不完全是您定义为“类似这样的东西”,因为它在属性名称中使用父名称。这是为了确保名称始终是唯一的,因为在技术上可能在不同的父母下拥有相同的孩子姓名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2020-03-12
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-17
    相关资源
    最近更新 更多