I have a very simple json and this code works for him:
function Get-CustomHeaders() {
return Get-Content -Raw -Path $JsonName | ConvertFrom-Json
}
However, if my json has any comments // wololo
it breaks. Would it be too hard to make this parser accept comments ?
PowerShell and JSON. To take advantage of JSON using PowerShell, we must be acquainted with two very important cmdlets: ConvertTo-JSON and ConvertFrom-JSON. (For those using PowerShell 7, be aware there have been changes and additions to the JSON cmdlets.) There are several ways to manipulate JSON files in PowerShell.
To convert the JSON file to the CSV file using PowerShell, we need to use the ConvertTo-CSV command as a pipeline. For example, we have a JSON file called PatchingServer. JSON stored at C:\temp and its content is as below.
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
The solution in the other answer only removes // comments
if they are at the beginning of a line (with or without spaces), and doesn't remove /* multiline comments */
This code removes all kind of //
and /* multiline comments */
/
$configFile = (Get-Content path-to-jsonc-file -raw)
# Keep reading, for an improvement
# $configFile = $configFile -replace '(?m)\s*//.*?$' -replace '(?ms)/\*.*?\*/'
As @Jiří Herník indicates in his answer, this expression doesn't have into account the case of strings with comments inside it, for example "url": "http://mydomian.com"
. To handle this case:
$configFile = $configFile -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'
for example removing the comments in this file:
{
// https://github.com/serilog/serilog-settings-configuration
"Serilog": {
"MinimumLevel": "Error", // Verbose, Debug, Information, Warning, Error or Fatal
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "D:\\temp\\MyService\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({App}) ({Environment}) {Message:lj}{NewLine}{Exception}"
}
},
{/*
"Name": "Seq",*/
"Args": {
"serverUrl": "http://localhost:5341"
}
}
]
}
}
results in:
{
"Serilog": {
"MinimumLevel": "Error",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "D:\\temp\\MyService\\log.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({App}) ({Environment}) {Message:lj}{NewLine}{Exception}"
}
} ,
{
"Args": {
"serverUrl": "http://localhost:5341"
}
}
]
}
}
Remove comment lines from your input before the conversion:
(Get-Content $JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With