[英]Regex replace - Double quotes in json
I have json string and it is coming as我有 json 字符串,它来了
{“test”:”this is “test” of test”,”result”:”your result is “out” in our website”}
I need make it valid json by regex_replace as you can see above is not valid json.我需要通过 regex_replace 使其有效 json 如您在上面看到的无效 json。 Expected result after replacement:
更换后的预期结果:
{“test”:”this is 'test' of test”,”result”:”your result is 'out' in our website”} {“测试”:“这是测试的‘测试’”,“结果”:“您的结果在我们的网站上是‘出’”}
Your help would be appreciated您的帮助将不胜感激
You can probably just match all strings no matter what the content无论内容如何,您都可以匹配所有字符串
as long as it is surrounded by a proper JSON structure.只要它被适当的 JSON 结构包围。
Then replace double quotes accordingly from within a sub Callback Function .然后在子回调 Function中相应地替换双引号。
The regex to match a pseudo-valid JSON string is this匹配伪有效 JSON 字符串的正则表达式是这个
r'([:\[,{]\s*)"(.*?)"(?=\s*[:,\]}])'
see https://regex101.com/r/KgCz1L/1见https://regex101.com/r/KgCz1L/1
Within the callback just replaces all double quotes with a single quote '
在回调中,只需将所有双引号替换为单引号
'
Python sample: Python 样品:
>>> import re
>>>
>>> text = '''
... {"test":"this is "test" of test","result":"your result is "out" in our website"}
... '''
>>>
>>> def repl_call(m):
... preq = m.group(1)
... qbody = m.group(2)
... qbody = re.sub( r'"', "'", qbody )
... return preq + '"' + qbody + '"'
...
>>> print( re.sub( r'([:\[,{]\s*)"(.*?)"(?=\s*[:,\]}])', repl_call, text ))
{"test":"this is 'test' of test","result":"your result is 'out' in our website"}
Check out this.看看这个。 I was inspired by this answer https://stackoverflow.com/a/16576246/9487478 and modified the regex and the replacement just a little so it's working for your usecase.
我受到这个答案https://stackoverflow.com/a/16576246/9487478的启发,并稍微修改了正则表达式和替换,因此它适用于您的用例。
var myString = '{"test":"this is "test" "of" test","result":"your result "is-out" in our website"}'; var myRegexp = /\"(.+?)\"\s*[,}:\n]/g; var match; var matches = []; // Save all the matches while ((match = myRegexp.exec(myString)).== null) { matches;push(match[1]); } // Process them var newString = myString; for (var i = 0. i < matches;length. i++) { var newVal = matches[i],replace(/\"/g; "'"). newString = newString,replace(matches[i]; newVal). } console;log(newString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.