to string java_Convert Bash String to JavaString

本文介绍了一种使用Perl语言处理JSON格式数据的方法。通过两次调用Perl脚本的方式,实现了将原始JSON字符串转换为带有换行符和转义字符的新字符串格式。此方法适用于需要对JSON数据进行格式化和转义处理的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Using a greatly adhoc approach: (invoking perl twice)

data='{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}'

echo $data |

perl -pe 's/{/{n/; s/}/n}/; s/, /,n/g; s/^"/ "/gm' |

perl -0pe 's/"/\"/g; s/n/\n" + n/g; s/^/"/gm; s/}\n.*$/}"/'

The result is:

"{n" +

" "5": ">10%",n" +

" "4": "<5%",n" +

" "3": ">28 months",n" +

" "2": "20%",n" +

" "1": 100n" +

"}"

Further testing:

test='{"first" : "1st", "second": "2nd", "third" : "3rd" }'

echo $test |

perl -pe 's/{/{n/; s/}/n}/; s/, /,n/g; s/^"/ "/gm' |

perl -0pe 's/"/\"/g; s/n/\n" + n/g; s/^/"/gm; s/}\n.*$/}"/'

returns

"{n" +

" "first" : "1st",n" +

" "second": "2nd",n" +

" "third" : "3rd" n" +

"}"

As for outputting this new string, try:

data='{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}'

newdata=$(echo $data |

perl -pe 's/{/{n/; s/}/n}/; s/, /,n/g; s/^"/ "/gm' |

perl -0pe 's/"/\"/g; s/n/\n" + n/g; s/^/"/gm; s/}\n.*$/}"/')

echo "String data = $newdata" >> /tmp/file.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值