Valid JSON giving JSONDecodeError: Expecting , delimiter
Asked Answered
J

2

74

I'm trying to parse a json response data from youtube api but i keep getting an error.

Here is the snippet where it choking:

data = json.loads("""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""")

..and this happens:

JSONDecodeError: Expecting , delimiter: line 1 column 23 (char 23)

I've confirmed that it's valid json and I have no control over the formatting of it so how can I get past this error?

Jagannath answered 6/2, 2012 at 6:34 Comment(1)
Also you might want to check your json if all lines end with commas except the last lineDisproof
P
101

You'll need a r before """, or replace all \ with \\. This is not something you should care about when read the json from somewhere else, but something in the string itself.

data = json.loads(r"""{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }""")

see here for more information

Plafker answered 6/2, 2012 at 6:39 Comment(6)
Ok but you need to explain why. The input needs to be passed a rawstring to avoid the \" backslash-escape being misinterpreted.Quechua
what's the solution if the string is stored in a variable?Relaxation
Store in it a variable as a rawstringTarah
How to store json in a variable as a raw string? @JacobBayerMorelli
@Morelli raw_json = r"""{ "entry":{...}}"""Sulemasulf
raw_s = r'{}'.format(s), fr"{orignal_string}" convert-regular-python-string-to-raw-string, string-and-bytes-literalsUnveiling
O
19

You need to add r before your json string.

>>> st = r'{ "entry":{ "etag":"W/\"A0UGRK47eCp7I9B9WiRrYU0.\"" } }'
>>> data = json.loads(st)
>>>
Obsequies answered 6/2, 2012 at 6:41 Comment(2)
I think it's better to use """ instead of ' to enclose the json because the data can have unescaped single quotes in it. Thanks for the answer.Jagannath
@ofko: I know that I just wrote this for clarity.Obsequies

© 2022 - 2024 — McMap. All rights reserved.