1

From this comment:

How does one remove the initial data: from a JSON file?

data: [
  {
    ...
  },
  {
    ...
  }
]

To make it look like this and be able to parse it properly.

[
  {
    ...
  },
  {
    ...
  }
]
uranibaba
  • 712
  • 1
  • 13
  • 30

3 Answers3

1
  • Get-Content reads a file line by line, which is wasted effort if the file's content is to be parsed as a whole as JSON.

    • The -Raw switch allows you to read the file as a whole, as a single, (usually) multi-line string.
  • The following solution uses -Raw and recognizes and removes any property name at the start of the file followed by :

(Get-Content -Raw -LiteralPath C:\path\path\file.json) -replace '^\w+:' |
  ConvertFrom-Json
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

First import the content of the file to a variable:

$json = gc -Path C:\path\path\file.json

Then (assuming this is in the first line of the file), replace the content of that line:

$json[0] = $json[0] -replace '^data:', ''

This will now work.

$json | ConvertFrom-Json

Example:

# File content
data: [
    {
        "_id": "630528cd19c645e4f1c6be6d",
        "index": 0,
        "guid": "ee49651d-1296-4165-bada-6491ce6081a6"
    }
]

PS> $json = Get-Content -path somefile.json
PS> $json[0] = $json[0] -replace '^data:', ''
PS> $json | ConvertFrom-Json

_id                      index guid
---                      ----- ----
630528cd19c645e4f1c6be6d     0 ee49651d-1296-4165-bada-6491ce6081a6
uranibaba
  • 712
  • 1
  • 13
  • 30
  • 1
    A more general answer would be to go generic and do `$json[0] = $json[0] -replace '^[^\[]*'`. That'll remove everything before the initial `[` on that first line, not just 'data: '. – TheMadTechnician Aug 23 '22 at 20:09
0

Using the PowerShell ConvertFrom-Json parser
(and ConvertTo-Json if even required to go back to Json):

$Data = @'
data: [
  {
    a: "..."
  },
  {
    a: "..."
  }
]
'@

(ConvertFrom-Json "{$data}").Data |ConvertTo-Json -Depth 9

[
  {
    "a": "..."
  },
  {
    "a": "..."
  }
]
iRon
  • 20,463
  • 10
  • 53
  • 79