python转义引号,Python:如何在json字符串值内转义双引号?

I'm having trouble parsing a json string in python because there are extra double quotes inside the string values like {"name": "Jack O"Sullivan", "id": "1"}

I'm trying to convert it into list for further evaluation like so:

import ast

js = '{"name": "Jack O"Sullivan", "id": "1"}'

ast.literal_eval(js).values()

How do I change the json string to be something like this "Jack O\'Sullivan", so that it evaluated properly.

Edit Just to stress that I know the json is invalid but this is what I've got and changing the source is NOT an option. I'm looking to work around this limitation at the moment.

解决方案import re

json = '{"name": "Jack O"Sullivan", "id": "1"}'

fixed = re.sub(r'("[\s\w]*)"([\s\w]*")',r"\1\'\2", json)

I suspect this will work (working example at repl.it), it uses the following regex:

("[\s\w]*)"([\s\w]*")

and then replacing any inner " with \'. This will work as long as the inclusion list is valid (the [\s\w]), ie valid strings will only include spaces and word characters. You may have to add additional possibilities for more complex names.

It matches any string """ and then replaces it with "\'" using capture groups and back references.

See the example at regex101

As I mentioned in the comments, the alternative is to make it exclude json control characters [^{}:,]. This should produce similar results, but won't miss names with other characters in them (like -, for example).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值