Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I parse a json string literal in python without modifying it?

This, is unambiguously a valid json string:

{"key": "quoted \"value\" and 'value'"}

…because of the ' and " in the value, both of these are invalid:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

json.parse("{"key": "quoted \"value\" and 'value'"}")
json.parse('{"key": "quoted \"value\" and 'value'"}')
> SyntaxError: invalid syntax

However, using triple quotes is also invalid:

json.loads("""{"key": "quoted \"value\" and 'value'"}""")
> JSONDecodeError: Expecting ',' delimiter: line 1 column 18 (char 17)

I get it, the reason for this is that \" is rendered as " by the multiline literal:

print("""{"key": "quoted \"value\" and 'value'"}""")
> {"key": "quoted "value" and 'value'"} <--- invalid json

So how do you do this?

In the trivial case I can manually fix the json, but in the complex case (hundreds of lines of json) this isn’t plausible.

The issue I’m trying to solve is manually replaying a request via a jupyter notebook; you copy the request body in chrome, and then want to replay it by pasting the request into the cell of a jupyter notebook.

>Solution :

You can use a raw triple-quoted string here, which treats backslashes as literal characters:

json.loads(r"""{"key": "quoted \"value\" and 'value'"}""")
> {'key': 'quoted "value" and \'value\''}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading