如何使用Powershell将JSON对象保存到文件?

Puz*_*zik 22 powershell json file

我已将以下JSON文件转换为powershell表示对象.

{
"computer": [
    {
        "children": [   
            {   
                "children": [ {
                   "children": [ {
                        "path": "T:\Dropbox\kvaki.html",
                        "name": "kvaki",
                        "type": "url",
                        "url": "http://example.com"
                   } ],
                    "path": "T:\Dropbox\",
                    "name": "Njusha",
                    "type": "folder"
                }, {
                    "path": "T:\Dropbox\Europa.html",
                    "name": "Europa",
                    "type": "url",
                    "url": "http://example.com"
                }, {
                    "path": "T:\Dropbox\math.html",
                    "name": "math",
                    "type": "url",
                    "url": "http://example.com"
                } ],
                "path": "T:\Dropbox\",
                "name": "Money",
                "type": "folder"
            }
        ],
        "full_path_on_file_sys": "T:\Dropbox\"
    }
]
Run Code Online (Sandbox Code Playgroud)

}

在使用powershell表示进行一些计算之后,我想将其作为JSON保存到文件中.但命令$jsonRepresentation | ConvertTo-Json | Out-File "D:\dummy_path\file.json"以这种方式保存它

{
    "computer":  [
                     {
                         "children":  " ",
                         "full_path_on_file_sys":  "T:\Dropbox\"
                     }
                 ]
}
Run Code Online (Sandbox Code Playgroud)

问题:如何实现正确保存复杂的PowerShell JSON表示?

Puz*_*zik 53

ConvertTo-Json的-depth参数解决了这个问题.

$jsonRepresentation | ConvertTo-Json -depth 100 | Out-File "D:\dummy_path\file.json"
Run Code Online (Sandbox Code Playgroud)

  • “Out-File”中的字符编码由“-Encoding”参数指定。 (4认同)
  • 对于任何想知道的人来说只是一个快速记录 - 默认深度为2,如果未在`ConvertTo-Json -depth x中指定 (3认同)
  • 我今天尝试了这个并注意到默认的`Out-File`产生了一个无法使用的文件([以UTF-16编码](/sf/ask/745905191/ file-what-is-the-difference)) 在 gulp 任务中的后续编程导入失败。查看十六进制编辑器可以清楚地说明这一点(并且 JSON 文件也没有在 VSCode 中使用 Intellisense 正确突出显示)。我采用了以下失败代码`$constants | ConvertTo-Json -depth 100 | Out-File $outFilePath` 并将其替换为 `$constants | ConvertTo-Json -depth 100 | 设置内容 $outFilePath` (2认同)

mjo*_*nor 8

只需将其传递给Set-Content或Out-File:

Get-Process powershell |
 ConvertTo-Json | 
 Set-Content json.txt
Run Code Online (Sandbox Code Playgroud)