Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert to JSON with comments from PowerShell

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 ?

like image 297
Gabriel Slomka Avatar asked Jun 27 '18 15:06

Gabriel Slomka


People also ask

Can I use JSON in PowerShell?

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.

How do I convert JSON data to CSV 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.

How JSON array looks like?

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.


2 Answers

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"
        }
      }
    ]
  }
}
like image 109
JotaBe Avatar answered Oct 03 '22 21:10

JotaBe


Remove comment lines from your input before the conversion:

(Get-Content $JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json
like image 25
Ansgar Wiechers Avatar answered Oct 03 '22 19:10

Ansgar Wiechers