将.txt文件数据转换为json格式

将.txt文件数据转换为json格式

我有user.txt日志文件,其中包含以下数据,我想将其转换为 json 格式。

{"user":"Demo Admin","user_id":"57c4718434243dc47d8b456c","org_id":"57c4718434243dc47d8b456b","superuser_id":null,"superuser_name":null,"application":"Trackier Webapp","method":"GET","ip":"43.249.54.66","domain":"demo.trackier.com","url":"https:\/\/demo.trackier.com\/admin.html","created":"2022-09-08 06:19:18","@timestamp":"2022-09-08T06:19:18Z"}
{"user":"Demo Admin","user_id":"57c4718434243dc47d8b456c","org_id":"57c4718434243dc47d8b456b","superuser_id":null,"superuser_name":null,"application":"Trackier Webapp","method":"GET","ip":"43.249.54.66","domain":"demo.trackier.com","url":"https:\/\/demo.trackier.com\/admin.html","created":"2022-09-08 06:19:35","@timestamp":"2022-09-08T06:19:35Z"}

答案1

假设您想将每行一个 json 的文件转换为一个 json 数组,您可以这样做:

sed '1s/^/[/;$s/$/]/;$!s/$/,/' < file.multijson > file.json

它会[在第一行的开头、]最后一行的末尾以及,除最后一行之外的所有行的末尾插入。

如果你有jq,你还可以这样做:

jq -s < file.multijson > file.json

(添加-c以获得紧凑的形式),但请注意它可能会重新格式化数字(例如将 1e1 或 10.0000000000000001 更改为 10)或字符串(例如更改"\u00e9""é")。

相关内容