我有一个包含以下行的文本文件:
TRACE 2016-06-23 08:47:54,803 {"x":"0.0000179000","l":"Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)","a":"Get","p":"345","u":"dae824a6-144b-4135-a6fd-01584f06a27f","i":"10.0.2.166","s":"US","e":"start"}
如果有人可以帮助如何使用powershell将其转换为JSON,那将会很棒(我尝试使用ConvertTo-JSON,但没有成功。)
答案 0 :(得分:3)
你想要的并不完全清楚。如果你想要一个有效的 JSON字符串,那么只需删除字符串的第一部分(这一部分:TRACE 2016-06-23 08:47:54,803
)和你的完成:
$data = 'TRACE 2016-06-23 08:47:54,803 {"x":"0.0000179000","l":"Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)","a":"Get","p":"345","u":"dae824a6-144b-4135-a6fd-01584f06a27f","i":"10.0.2.166","s":"US","e":"start"}'
$json = $data.Substring($data.IndexOf("{"))
如果你想将它从JSON转换为对象,那么你仍然需要将字符串转换为有效的JSON字符串然后你可以这样做:
$myObject = ConvertFrom-Json $json
答案 1 :(得分:0)
# 'TRACE 2016-06-23 08:47:54,803 {"x":"0.0000179000","l":"Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.34209)","a":"GetUserStartedWatchingMedias","p":"195","u":"dae824a6-144b-4135-a6fd-01584f06a27f","i":"10.0.2.166","s":"EU-WS-A-5","e":"start"}'
foreach ($row in (Get-Content -LiteralPath C:\TEMP\IIS_Logs\IIS_Logs.txt ) )
{
if ($row -like '*}')
{
$Arr = $row -split ' ' ;
$Arr = $Arr -ne ' ' ;
$RecordDate = $Arr[1]+' '+$Arr[2];
$Json = $row.Substring($row.IndexOf("{"),($row.IndexOf("}")-$row.IndexOf("{")+1));
ConvertFrom-Json -InputObject $Json | ConvertTo-Csv -Delimiter "," -NoTypeInformation | Out-File 'C:\TEMP\IIS_Logs\test.txt'
};
};