Praful Bagai
Praful Bagai

Reputation: 17382

Python - `\n` in json

I'm using POSTMAN to send the POST data. After posting the data, I body I receive in request.body is

{
  "title": "Kill Bill: Vol. 2","content":
  "http://netflixroulette.net/api/posters/60032563.jpg\n\nabcdefrefbqwejf\n\nq efjqwefqwrf aksks"
}

I want to json.loads the body. However, I've new line character in my json.

So, I first replace \n with \\n and then do json.loads. But after replacing \n with \\n, the string I receive is :-

{\n  "title": "Kill Bill: Vol. 2","content":\n  "http://netflixroulette.net/api/posters/60032563.jpg\n\nabcdefrefbqwejf\n\nq efjqwefqwrf aksks"\n}

And then when I do json.loads, it results in error. This is because of new line character at the start of string and at various other locations as well.

Any idea how can I treat this?

Upvotes: 2

Views: 12444

Answers (1)

informaton
informaton

Reputation: 1482

It seems you are replacing the actual newline character '\n' instead of the text "\n".

If you want to remove the newline strings "\n" in your content, and replace them with actual newlines, try replacing "\\n" with '\n' (i.e. and not vice versa).

FOLLOW-ON Answer

Here's how it works, in my understanding:

Looking at your first and second line of the request.body

{
  "title": "Kill Bill ....

There is actually a newline character ('\n') at the end of the first line. We don't see it, because it is being interpreted so to speak. It is one of the many non-printable characters which affect formatting when seen and interpreted by various programs (e.g. a text editor/viewer). What you were trying to do originally was replace the "\n"'s that you were seeing the Content part of your .json body. These ones:

... 3.jpg\n\nab\n\nq ...

The trouble is that the backslash '\' is used to escape normal characters and access special, non-printable characters. So by asking to replace '\n' with '\\n' you were actually replacing the line breaks with the string "\\n". You can see that what you wanted changed, the "\n\n"'s were still there, and instead new "\n"'s started appearing (i.e. hence your quesiton).

It helps me to remember in these cases, how you would go about printing a newline string so that it is not interpreted as a newline, but shows up as "\n" and not like

this (the invisible one that is actually a break). To print out this string, you would need to let the interpreter/text editor understand that you in fact want the '\' character to be printed and not a follow-on escaped character. Because the '\' indicates a follow-on escape command, it has its own escape symbol, which is itself. That is, to show a '\' in a formatted string, you put it twice, like so "\\". Thus, even though it looks like

  ... 3.jpg\n\nab\n\nq ...

You would have needed to format it like

  ... 3.jpg\\n\\nab\\n\\nq ...

to get it to look the way it does.

Upvotes: 5

Related Questions