【发布时间】:2019-09-18 23:33:06
【问题描述】:
我正在尝试将文本文件转换为 JSON 格式的字符串,但双引号的位置不正确。
我的 file.txt 包含以下结构化信息(开头也有两个空行):
adapter_name : empty1
route_age : 10
route_nexthop : 172.0.0.1
route_protocol : NETMGMT1
speed : null
adapter_name : empty2
route_age : 100
route_nexthop : 172.0.0.2
route_protocol : NETMGMT2
speed : null
adapter_name : empty3
route_age : 1000
route_nexthop : 172.0.0.3
route_protocol : NETMGMT3
speed : null
我的代码是:
$data = Get-Content C:\scripts\file.txt | %{$_.PSObject.BaseObject}
$data | ConvertTo-Json
没有这部分:
%{$_.PSObject.BaseObject}
它只是深入到对象树中,这可能需要很长时间。
实际结果是:
[
"",
"",
"adapter_name : empty1",
"route_age : 10",
"route_nexthop : 172.0.0.1",
"route_protocol : NETMGMT1",
"speed : null "
"",
"adapter_name : empty2",
"route_age : 100",
"route_nexthop : 172.0.0.2",
"route_protocol : NETMGMT2",
"speed : null "
"",
"adapter_name : empty3",
"route_age : 1000",
"route_nexthop : 172.0.0.3",
"route_protocol : NETMGMT3",
"speed : null "
]
而预期的结果是:
[
{
"adapter_name" : "empty1",
"route_age" : 10,
"route_nexthop" : "172.0.0.1",
"route_protocol" : "NETMGMT1",
"speed" : null
},
{
"adapter_name" : "empty2",
"route_age" : 100,
"route_nexthop" : "172.0.0.2",
"route_protocol" : "NETMGMT2",
"speed" : null
},
{
"adapter_name" : "empty3",
"route_age" : 1000,
"route_nexthop" : "172.0.0.3",
"route_protocol" : "NETMGMT3",
"speed" : null
}
]
https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-6 链接中的示例 4 和 5 显示了如何在类似情况下使用 cmdlet ConvertoTo-Json,但没有问题。
【问题讨论】:
标签: powershell