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.
[
{
...
},
{
...
}
]
CodePudding user response:
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
CodePudding user response:
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
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
CodePudding user response:
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": "..."
}
]