I am trying to convert a text file to a JSON-formatted string, but the double-quotation marks are not correctly positioned.
My file.txt contains the following structured information (two empty lines at the beginning as well):
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.