简体   繁体   English

如何在Shell脚本中删除Json文件中字符串周围的多余引号

[英]how to remove extra quotes around the string in Json file in shell script

I want to remove extra quote from the below Json 我想从下面的Json中删除多余的报价

{""id"":""1"", ""name"":""john"",""address"":"",""timestamp"":""2018/01/01 12:43:42 -700"",""dept"":""}

I am using the sed command for this: 我为此使用sed命令:

sed -i -e 's/""/"/g' file.json

However it's not working as expected because the values for address and dept are just the empty string "" and I don't want to replace those by just a single " which would be a new JSON syntax error. I want to replace only the doubled double quotes around fields which contain an actual value. So I tried 但是,它不能按预期工作,因为addressdept的值只是空字符串""而我不想将它们替换为一个" ,这将是一个新的JSON语法错误。我只想替换成double的在包含实际值的字段周围用双引号引起来,所以我尝试了

sed -i -e 's/\""[a-z]+[0-9]+[.-]+\""/"[a-z]+[0-9]+[.-]+\"/g' file.json 

but it's not working either. 但它也不起作用。

How can I achieve this? 我该如何实现?

Assuming keys and values don't contain escaped commas or double-quotes: 假设键和值不包含转义逗号或双引号:

sed -i 's/""\([^",]\+\)""/"\1"/g' file

[^",] matches any character but " and , , \\+ means one or more. [^",]匹配任何字符,但",\\+表示一个或多个。 enclosing it in escaped parentheses ( \\(\\) ) populates capturing group 1 ( \\1 in replacement string expands to it). 将其括在转义括号( \\(\\) )中会填充捕获组1(替换字符串中的\\1会展开到它)。 So, ""\\([^",]\\+\\)"" matches two double-quotes, followed by one or more characters which are not commas or double-quotes, followed by two double-quotes. 因此, ""\\([^",]\\+\\)""匹配两个双引号,然后是一个或多个非逗号或双引号的字符,然后是两个双引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM