gpt4 book ai didi

json - 使用 PowerShell 中的注释转换为 JSON

转载 作者:行者123 更新时间:2023-12-02 12:14:01 25 4
gpt4 key购买 nike

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

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

但是,如果我的 json 有任何注释 //wololo 它就会中断。让这个解析器接受评论会不会太难了?

最佳答案

另一个答案中的解决方案仅删除位于行开头(有或没有空格)的 //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"。处理这种情况:

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

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

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

关于json - 使用 PowerShell 中的注释转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com