使用 UNIX 命令行工具将 JSON 拆分为多行
Split a JSON to multiple lines using UNIX command line tools
我们有一个 JSON 文件需要多行而不是单行,如下所示,
{this is the first block},{this is the second block, really},{this is the third you're kidding:no}
我们希望它是这样的,这样它就可以被提供给外部程序来毫无问题地读取它,
{this is the first block}
{this is the second block, really}
{this is the third you're kidding:no}
我不是 awk、sed、cut 等简单文本处理工具的专家,但我确实尝试过使用 sed 一段时间但没有成功。
cat test.json | sed 's/},/\n/g'
{this is the first block
{this is the second block, really
{this is the third you're kidding:no}
最好的方法是什么?
因为它不是 JSON 而你只是想拆分:
input_file
{this is the first block},{this is the second block, really},{this is the third you're kidding:no}
sed 's/},/}\n/g' input_file
output
{this is the first block}
{this is the second block, really}
{this is the third you're kidding:no}
Awk 替代方案:
awk 'BEGIN { RS="(,?{)|(},?)" } /[[:alnum:]]/ { print [=10=]="{"[=10=]"}" }' file
将记录分隔符设置为一个或多个逗号和{或}以及一个或多个逗号。然后,当遇到字母数字字符串时,将 { 添加到字符串前,附加 } 并打印
我们有一个 JSON 文件需要多行而不是单行,如下所示,
{this is the first block},{this is the second block, really},{this is the third you're kidding:no}
我们希望它是这样的,这样它就可以被提供给外部程序来毫无问题地读取它,
{this is the first block}
{this is the second block, really}
{this is the third you're kidding:no}
我不是 awk、sed、cut 等简单文本处理工具的专家,但我确实尝试过使用 sed 一段时间但没有成功。
cat test.json | sed 's/},/\n/g'
{this is the first block
{this is the second block, really
{this is the third you're kidding:no}
最好的方法是什么?
因为它不是 JSON 而你只是想拆分:
input_file
{this is the first block},{this is the second block, really},{this is the third you're kidding:no}
sed 's/},/}\n/g' input_file
output
{this is the first block}
{this is the second block, really}
{this is the third you're kidding:no}
Awk 替代方案:
awk 'BEGIN { RS="(,?{)|(},?)" } /[[:alnum:]]/ { print [=10=]="{"[=10=]"}" }' file
将记录分隔符设置为一个或多个逗号和{或}以及一个或多个逗号。然后,当遇到字母数字字符串时,将 { 添加到字符串前,附加 } 并打印