我有一个文件,其中每一行都是一个JSON对象。我希望将该文件转换为JSON数组。
该文件如下所示:
{"address":"email1@foo.bar.com", "topic":"Some topic."}
{"address":"email2@foo.bar.com", "topic":"Another topic."}
{"address":"email3@foo.bar.com", "topic":"Yet another topic."}我使用bash和jq。
我试过了
jq --slurp --raw-input 'split("\n")[:-1]' my_file但这只是将每一行视为一个字符串,创建一个JSON字符串数组。
[
"{\"address\":\"email1@foo.bar.com\", \"topic\":\"Some topic.\"}",
"{\"address\":\"email2@foo.bar.com\", \"topic\":\"Another topic.\"}",
"{\"address\":\"email3@foo.bar.com\", \"topic\":\"Yet another topic.\"}"
]我想要:
[
{"address":"email1@foo.bar.com", "topic":"Some topic."},
{"address":"email2@foo.bar.com", "topic":"Another topic."},
{"address":"email3@foo.bar.com", "topic":"Yet another topic."}
]发布于 2020-03-11 23:18:41
发布于 2020-03-12 01:31:12
对于手头的任务,使用jq的"slurp“选项或[inputs]会导致潜在的巨大资源浪费。
一个琐碎但高效的解决方案可以在awk中实现,如下所示:
awk 'BEGIN {print "[";} NF==0{next;} n=="" {print;n++;next;} {print ","; print;} END {print "]"}'在jq中,可以使用foreach和inputs实现一个等效的高效解决方案,并将其作为练习。
https://stackoverflow.com/questions/60637859
复制相似问题