Getting extra \ in python json file output

Hello

I am importing json data from rest API and while printing data in python it looks good, even while copying the output from postman, it is good and nicely indented too. However while writing data to a json file, I see extra \ added inplace of actual newline characters and no indentation coming even if I mention indent=4 and I am not sure how can I resolve this problem? Can it be because of characterset difference between the api data and python and in that case what can be done? Or any workaround, I appreciate your response a lot.

Json encoded data, is just a string (it’s string encoding independent, unlike toml which must be utf-8). If the response json, contains string fields that themselves contain new line characters, the json spec requires those to be represented as \n, (just the same as in Python and many other languages. But note, JSON requires double quotes.).

However, when the Json string encoding, of such a json object or array, containing strings, that contain new lines, is loaded into Python, the \ and the n are different characters (code points), The repr of the JSON encoding in Python (the string literal you would need to type to hard code the same JSON string) must also escape the backslash itself (or use a raw string, e.g. len(r'\n') == 2 = 1 + len('\n')).

Also note, representing and loading JSON text in Python, (which is what I’m suggesting could cause the extra \) is different to loading the JSON and converting it into Python data types (with json.load). If the latter is done, the resulting dict should just contain string literals with single new line chars.

2 Likes

Thanks, it works

Glad to hear that. Thanks for letting me know :slightly_smiling_face:.