使用PowerShell的注释转换为JSON [英] Convert to JSON with comments from PowerShell

查看:84
本文介绍了使用PowerShell的注释转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的json,下面的代码对他有用:

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

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

但是,如果我的json有任何注释// wololo,它将中断.使此解析器接受注释是否太难了?

However, if my json has any comments // wololo it breaks. Would it be too hard to make this parser accept comments ?

推荐答案

另一个答案中的解决方案仅将// comments删除(如果它们位于行的开头)(带或不带空格),而不会删除/* multiline comments */

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 */

此代码删除了所有///* multiline comments *//

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

正如@JiříHerník在他的回答中指出的那样,该表达式无需考虑其中带有注释的字符串的大小写,例如"url": "http://mydomian.com".要处理这种情况:

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"
        }
      }
    ]
  }
}

导致:

{

  "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"
        }
      }
    ]
  }
}

这篇关于使用PowerShell的注释转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆