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

时间:2014-03-08 22:11:57

标签: json file powershell

我已将以下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\"
    }
]

}

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

{
    "computer":  [
                     {
                         "children":  " ",
                         "full_path_on_file_sys":  "T:\Dropbox\"
                     }
                 ]
}

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

6 个答案:

答案 0 :(得分:52)

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

$jsonRepresentation | ConvertTo-Json -depth 100 | Out-File "D:\dummy_path\file.json"

答案 1 :(得分:8)

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

Get-Process powershell |
 ConvertTo-Json | 
 Set-Content json.txt

答案 2 :(得分:1)

如果您遇到PowerShell版本2,the JSON module of Joel Bennett from the 'PowerShell Code Repository'可能会有所帮助。

答案 3 :(得分:0)

如果要同时查看输出并将其保存到文件,可以使用tee命令。

Get-Process powershell | ConvertTo-Json |  Tee-Object json.txt

答案 4 :(得分:0)

$json.properties.metadata | ConvertTo-Json -Compress

答案 5 :(得分:-1)

1)以下命令可用于将json转换为CSV

示例: Get-Content package.json | Out-String | ConvertFrom-Json | Select parameter1, parameter2, parameter3 | ConvertTo-Csv -NoTypeInformation | Format-Table >> C:\JenkinsWorkspace\Result.csv

Get-Content:类似于Linux中的“ cat”命令,它将获取文件“ package.json”的所有数据并从Json转换(使用ConvertFrom-Json函数),仅提取所需参数的详细信息,然后进行转换使用“ ConvertTo-Csv”功能将其转换为CSV,而无需任何不需要的类型标题并将其格式化为表格。

2)也可以将上述结果格式化为适当的csv,以Excel格式查看,没有任何重复,也可以使用以下命令进行“文本到列”转换:

Import-Csv "C:\Result.csv" -delimiter "," | Sort-Object _from -Unique | Export-csv "C:\FINAL_REPORT_$date.csv"

相关问题