1

I want to read my JSON file and write the same file with a rearranged code. My JSON file give me something like that:

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

But I want something like this

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

Here's the code I use:

$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

I also use another piece of code that give me what I want but only in the terminal, when I use Set-Content the output looks like this:

"{ \'id'\ 536453 }"

Here's the code:

(New-Object PSObject |
    Add-Member -PassThru NoteProperty id $json118.stats.splits.getId
) | ConvertTo-Json
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

2 Answers2

2

What you need is,

  • Convert the Json to Object

  • Select the required member

  • Convert back to json

    $Data = $JsonString | ConvertFrom-Json
    
    $Data.One.Two.Data | ConvertTo-Json
    
Prasoon Karunan V
  • 2,916
  • 2
  • 12
  • 26
1

Using this 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

Result:

{
    "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"
}

It is not exactly what you defined as "Something like this" because it uses the parent names in the property names. This is to make sure that the names are always unique as it is technical possible to have the same child names under different parents.

iRon
  • 20,463
  • 10
  • 53
  • 79