Powershell通过评论转换为json

Gab*_*mka 5 powershell json

我有一个非常简单的json,这段代码适合他:

function Get-CustomHeaders() {
   return Get-Content -Raw -Path $JsonName | ConvertFrom-Json
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我的json有任何意见,// wololo它会打破.让这个解析器接受评论会难吗?

Jot*_*aBe 9

另一个答案中的解决方案仅// comments在它们位于行首(有或没有空格)时才会删除,并且不会删除/* multiline comments */

此代码删除所有类型的///* multiline comments *//

$configFile = (Get-Content path-to-jsonc-file -raw)
# Keep reading, for an improvement
# $configFile = $configFile -replace '(?m)\s*//.*?$' -replace '(?ms)/\*.*?\*/'
Run Code Online (Sandbox Code Playgroud)

正如@Ji?í Herník 在他的回答中指出的那样,这个表达式没有考虑其中包含注释的字符串的情况,例如"url": "http://mydomian.com"。要处理这种情况:

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

例如删除此文件中的注释:

{
  // 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"
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

{

  "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"
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)


Ans*_*ers 7

转换前从输入中删除注释行:

(Get-Content $JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json
Run Code Online (Sandbox Code Playgroud)

  • 此外,PowerShell Core 6 开箱即用地支持 Json 文件中的注释 (2认同)

Jiř*_*ník 5

在这里,您有一个无法通过以前的答案正确处理的示例:

{
"url":"http://something" // note the double slash in URL
}
Run Code Online (Sandbox Code Playgroud)

所以这里是正则表达式,它也解决了这个问题。

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

重要的提示:

Powershell 6.0+可以加载带有注释的 JSON。