This might seem stupid to you but I noticed something and I just dont udnerstand it.
h = '[{"b": [2, 4], "c": 3.0, "a": "A"}]'
json.loads(h)
This will work, but this:
h = '"[{"b": [2, 4], "c": 3.0, "a": "A"}]"'
json.loads(h)
Will raise an exepction JSONDecodeError: Extra data: line 1 column 5 (char 4)
h = '"hey"'
json.loads(h)
This will also work.
Can someone please explain to me the differences between ''','" and '?
CodePudding user response:
Consider the middle example, from the perspective of individual strings (within your strin), you are asking json to load. By adding the first "
, you are shifing all strings by one:
h = '"[{"b": [2, 4], "c": 3.0, "a": "A"}]"'
-- ---------- ------- --
Strings surrounded by quotes
So when you first reach a non string b
, json has no idea what to do with it. If you want to treat the entire content as a string, you need to escape the quotes \\"
. So it would look like this:
h = '"[{\\"b\\": [2, 4], \\"c\\": 3.0, \\"a\\": \\"A\\"}]"'
CodePudding user response:
It's saying that the character number 4 is not recognized.
That's normal, the decoder goes like that
char 0 " --> this is a string start
char 1 [ --> this is inside the string
char 2 { --> this is inside the string
char 3 " --> this is the end of the string
char 4 b --> this has nothing to do here, stop execution and raise error
CodePudding user response:
Here
h = '"[{"b": [2, 4], "c": 3.0, "a": "A"}]"'
you are attempting to use "
for 2 different meanings: as string delimiter (1st and last) and literal "
(all others). In such case way of escaping is required to tell that "
is literally "
consider what would be effect of following dumps
import json
text = 'this text does contain "quotation" marks'
print(json.dumps(text))
gives output
"this text does contain \"quotation\" marks"
Note \
pointing literal "
.