我试图将文本文件转换为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
My code is:
$data = Get-Content C:\scripts\file.txt | %{$_.PSObject.BaseObject}
$data | ConvertTo-Json
Without this part: %{$_.PSObject.BaseObject}
It's just descending very deeply into the object tree which could take a long time.
The actual result is:
[
"",
"",
"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 "
]
And the expected result is:
[
{
"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
}
]
The examples 4 and 5 in the link https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-6 show how to use the cmdlet ConvertoTo-Json with a similar situation, but without problems.发布于 2019-09-19 04:04:40
Get-Content只是从文本文件中返回单独的行,它不知道这些行中可能编码的任何结构。
因此,您只需将行形式转换为JSON,这将生成您正在看到的JSON字符串值的平面列表。
要解决这个问题,您必须自己将文本文件解析为结构化对象(哈希表),分块地将它们传递给ConvertTo-Json。
# Read the input file as a whole (-Raw) and split it into blocks (paragraphs)
(Get-Content -Raw C:\scripts\file.txt) -split '\r?\n\r?\n' -ne '' |
ForEach-Object { # Process each block
# Initialize an ordered hashtable for the key-values pairs in this block.
$oht = [ordered] @{}
# Loop over the block's lines.
foreach ($line in $_ -split '\r?\n' -ne '') {
# Split the line into key and value...
$key, $val = $line -split ':', 2
# ... and add them to the hashtable.
$oht[$key.Trim()] = $val.Trim()
}
$oht # Output the hashtable.
} | ConvertTo-Json上面的输出产生了所需的输出。
作为一个旁白,关于:
没有这一部分:
%{$_.PSObject.BaseObject}它只是深入到对象树中,这可能需要很长时间。
问题是,Get-Content用额外的、通常是不可见的属性来修饰它输出的行,这些属性提供原始信息,例如从这些行读取的文件的路径。
这些通常隐藏的属性意外地出现在序列化场景中,例如在使用ConvertTo-Json时。
上面的解决方案隐式地绕过了这个问题,因为在处理过程中正在创建新的字符串。
虽然附加的属性可能很有用,但它们不仅经常是不需要的,而且还减缓了Get-Content的速度。
Get-Content中添加一个开关,允许选择不装饰行( PowerShell Core7.0.0-Preview.3未实现)。[string] (未在PowerShell Core7.0.0-Preview.3中实现)。https://stackoverflow.com/questions/58001914
复制相似问题