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).

你可能感兴趣的:(python转义引号)