2 回答
TA贡献1998条经验 获得超6个赞
我尝试了正则表达式方法,但发现它既复杂又缓慢。所以我写了一个简单的“括号解析器”来跟踪当前的引用模式。它不能做多个嵌套,你需要一个堆栈。对于我将 str(dict) 转换为正确的 JSON 的用例,它可以工作:
示例输入: {'cities': [{'name': "Upper Hell's Gate"}, {'name': "N'zeto"}]}
示例输出: {"cities": [{"name": "Upper Hell's Gate"}, {"name": "N'zeto"}]}'
python单元测试
def testSingleToDoubleQuote(self):
jsonStr='''
{
"cities": [
{
"name": "Upper Hell's Gate"
},
{
"name": "N'zeto"
}
]
}
'''
listOfDicts=json.loads(jsonStr)
dictStr=str(listOfDicts)
if self.debug:
print(dictStr)
jsonStr2=JSONAble.singleQuoteToDoubleQuote(dictStr)
if self.debug:
print(jsonStr2)
self.assertEqual('''{"cities": [{"name": "Upper Hell's Gate"}, {"name": "N'zeto"}]}''',jsonStr2)
单引号到双引号
def singleQuoteToDoubleQuote(singleQuoted):
'''
convert a single quoted string to a double quoted one
Args:
singleQuoted(string): a single quoted string e.g. {'cities': [{'name': "Upper Hell's Gate"}]}
Returns:
string: the double quoted version of the string e.g.
see
- https://stackoverflow.com/questions/55600788/python-replace-single-quotes-with-double-quotes-but-leave-ones-within-double-q
'''
cList=list(singleQuoted)
inDouble=False;
inSingle=False;
for i,c in enumerate(cList):
#print ("%d:%s %r %r" %(i,c,inSingle,inDouble))
if c=="'":
if not inDouble:
inSingle=not inSingle
cList[i]='"'
elif c=='"':
inDouble=not inDouble
doubleQuoted="".join(cList)
return doubleQuoted
TA贡献1802条经验 获得超4个赞
几种方式,一种是使用regex模块与
"[^"]*"(*SKIP)(*FAIL)|'
在 regex101.com 上查看演示。
在Python:
import regex as re
rx = re.compile(r'"[^"]*"(*SKIP)(*FAIL)|\'')
new_string = rx.sub('"', old_string)
对于原始re模块,您需要使用一个函数并查看该组是否已匹配 -(*SKIP)(*FAIL)让您完全避免这种情况。
添加回答
举报