gpt4 book ai didi

json - Powershell 转换为 Json 格式错误

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

我正在使用 win_shell 将 powershell 输出转换为 json 格式,以便稍后对其进行过滤。问题是我的 Json 格式不好。

这是代码

    - win_shell: |
Get-ChildItem -Path <some_path> |
Where-Object {$_.PSIsContainer} | Sort-Object LastWriteTime -Descending |
Select-Object -First 20 | ConvertTo-Json
register: register_results

- debug:
var: register_results

我得到的标准输出行不干净,不能用于 json 过滤器:

  "stderr": "",
"rc": 0,
"stdout_lines": [
"[",
" {",
" \"Name\": \"976\",",
" \"FullName\"\"F:\\\\some\\\\path\\\\to\\\\folder\\\\976\",",
" \"Parent\": {",
" \"Name\": \"first\",",
" \"Parent\": \"All\",",
" \"Exists\": true,",
" \"Root\": \"F:\\\\\",",
" \"Extension\": \"\",",
etc...

当我尝试过滤例如“parent”或“Name”时,这些额外的空格会导致错误。看起来“ConvertToJson”旁边必须有其他参数才能使输出更清晰。

有什么办法吗?

最佳答案

根据 this postConvertTo-Json 的 JSON 格式计划在 PowerShell 6 中得到改进。您可以像帖子建议的那样在 ConvertTo-Json 之后自己覆盖格式。提到的帖子中的一些代码可能会解决您的问题:

# Formats JSON in a nicer format than the built-in ConvertTo-Json does.
function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) {
$indent = 0;
($json -Split '\n' |
% {
if ($_ -match '[\}\]]') {
# This line contains ] or }, decrement the indentation level
$indent--
}
$line = (' ' * $indent * 2) + $_.TrimStart().Replace(': ', ': ')
if ($_ -match '[\{\[]') {
# This line contains [ or {, increment the indentation level
$indent++
}
$line
}) -Join "`n"
}

$obj = @{}
$json = $obj | ConvertTo-Json | Format-Json

或者,您应该能够使用 ConvertTo-JsonNewtonsoftNewtonsoft.Json直接通过安装和导入模块并使用它代替 ConvertTo-Json...

Install-Module Newtonsoft.Json
Import-Module Newtonsoft.Json

$obj = @{}
$json = $obj | ConvertTo-JsonNewtonsoft

# or Newtonsoft.Json directly (same code)

$obj = @{}
$json = [Newtonsoft.Json.JsonConvert]::SerializeObject($obj, [Newtonsoft.Json.Formatting]::Indented)

关于json - Powershell 转换为 Json 格式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57329639/

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