Home > Back-end >  Difficulty understanding JSON escape characters
Difficulty understanding JSON escape characters

Time:02-24

I'm quite new to programming and recently have dived into the topic of JSON Escape and special characters in Python. I understand how to escape double quotation marks. For example:

import json

data = json.loads('{"Test": "In \\"quotation\\" marks"}')

print(data)

returns(as a "dict"): {'Test': 'In "quotation" marks'}

But I can't wrap my head around how the other special characters would be used like: \b, \n, \, \f etc...

Could someone please show me some examples of code where and how those other special escape characters would be used in, say for example, a json.loads functions like above. I'd be very grateful. Thanks

CodePudding user response:

JSON strings must be double quoted; as such, you need to escape a double quote in order to include it in a JSON string.

However, you also need to escape the backslash in the Python string literal in order to get a literal backslash in the JSON value. You can do that as you show in your question:

'{"Test": "In \\"quotation\\" marks"}'

or by using a raw string literal

r'{"Test": "In \"quotation\" marks"}'

Part of the confusion comes from the fact that JSON string values and Python string literals can look identical. For example, a JSON string that consists of a linefeed would look like

"\n"

and a Python string literal defining a string that consists of a linefeed would also look like

"\n"

A Python string literal defining a string that contains a JSON string consisting of a line feed would then be either

'"\\n"'

or

r'"\n"'

CodePudding user response:

Nevermind. I figured it out. My problem was that when I was doing

data = json.loads('{"Test": "In quotation \\n marks"}')

print(data)

it would return: {'Test': 'In quotation \n marks '} and I was trying to understand why it shows \n instead of an actual new line

I realized the escapes only show up when you look for value of a given key. So for example,

print(data["Test"]) returned

In quotation

marks

same thing for data = json.loads('{"Test": "In "quotation" \\bmarks"}')

returns = In quotationmarks

  • Related