Convert to JSON with comments from PowerShell

前端 未结 3 462
逝去的感伤
逝去的感伤 2021-01-12 05:56

I have a very simple json and this code works for him:

function Get-CustomHeaders() {
   return Get-Content -Raw -Path $JsonName | ConvertFrom-Json
}
         


        
相关标签:
3条回答
  • 2021-01-12 05:58

    Remove comment lines from your input before the conversion:

    (Get-Content $JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json
    
    0 讨论(0)
  • 2021-01-12 06:04

    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"
            }
          }
        ]
      }
    }
    
    0 讨论(0)
  • 2021-01-12 06:10

    Here you have an example which can't be handled right by previous answers:

    {
    "url":"http://something" // note the double slash in URL
    }
    

    so here is regexp that solves also this problem.

    $configFile = $configFile -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'
    

    IMPORTANT NOTE:

    Powershell 6.0+ can load JSON with comments in it.

    0 讨论(0)
提交回复
热议问题