简体   繁体   English

正则表达式将字符串“to”中的所有双引号替换为有效的json字符串

[英]Regex to replace all double quotes in a string “ to \” to valid json string

I have a invalid json string like {"subject":"tv 60" new","body":"contact me for detail"}. 我有一个无效的json字符串,如{“subject”:“tv 60”new“,”body“:”联系我以获取详细信息“}。

And i try to use php preg_replace to valid this json string but fail. 我尝试使用php preg_replace来验证这个json字符串但是失败了。

Please help me to create a regex to replace the " to /" . 请帮我创建一个正则表达式来替换“to /”。

Thanks in advance. 提前致谢。

Assuming that the '{', ':' and the ',' characters in your JSON don't have any trailing space between them and the double quotes, a solution could be this: 假设JSON中的'{',':'和','字符在它们和双引号之间没有任何尾随空格,解决方案可能是这样的:

$sanitizedJsonString = preg_replace('/([^:,{])"([^:,}])/', "$1".'\"'."$2", $yourMalformedJsonString);

It finds all the blockquotes not preceded by the '{', ':' or ',' characters and not followed by the ':', ',' or '}' characters and replaces them with the '\\"' character. 它发现所有的块引用前面没有'{',':'或','字符,后面没有':',','或'}'字符,而是用'\\“'字符替换它们。


Hopefully it solve your problems, however keep in mind that there are some special cases in which this approach fails: for example, if inside your malformed JSON you have a word inside blockquotes that is followed by a comma like this: 希望它可以解决您的问题,但请记住,有一些特殊情况会导致此方法失败:例如,如果在您的格式错误的JSON中,您在blockquotes中有一个单词后跟一个逗号,如下所示:

{"subject":"tv 60" new","body":"contact "me", for detail"}

you'll still have a not valid JSON: 你仍然有一个无效的JSON:

{"subject":"tv 60\" new","body":"contact \"me", for detail"}

If you need a more reliable solution I agree with Steve P., you have to implement a script that parses your string and make the replacements of the blockquotes when required. 如果你需要一个更可靠的解决方案我同意Steve P.,你必须实现一个脚本来解析你的字符串并在需要时替换blockquotes。

$string =~ /(?!<[\{:,])\"(?!\s*[:,\}]/\\"/g  

这个正则表达式查找任何“不遵循a:a或a {并且不跟随a:a或a}并且用\\字符引用它。这应该适合你。

Unless you're regular expressions to validate the keys/values prior to insertion into the JSON object, using regular expressions is not a good way to attempt to validate a given JSON object. 除非您是在插入JSON对象之前验证键/值的正则表达式,否则使用正则表达式不是尝试验证给定JSON对象的好方法。

Even if you are attempting to validate upon insertion, it seems like regex is overkill and instead you can just use various helper methods or simply iterate through the raw string and replace when necessary. 即使您尝试在插入时进行验证,似乎正则表达式也是过度的,而您只需使用各种辅助方法或只是遍历原始字符串并在必要时进行替换。

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

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