Python: Handling newlines in json.load() vs json.loads()

EDITED: Already answered here: https://stackoverflow.com/a/16544933/1054458

Maybe the strict option can help:

test.py:

import json

s = '''{
"asdf":"foo
bar"
}'''

print(json.loads(s, strict=False)["asdf"])

output:

$> python test.py
foo
bar

json.load() reads from a file descriptor and json.loads() reads from a string.

Within your file, the \n is properly encoded as a newline character and does not appear in the string as two characters, but as the correct blank character you know.

But within a string, if you don't double escape the \\n then the loader thinks it is a control character. But newline is not a control sequence for JSON (newline is in fact a character like any other).

By doubling the backslash you actually get a real string with \n in it, and only then will Python transform the \n into a newline char.