user3117473
user3117473

Reputation: 3

json.JSONDecoder().decode() can not work well

code is simple, but it can not work. I don't know the problem

import json

json_data = '{text: \"tl4ZCTPzQD0k|rEuPwudrAfgBD3nxFIsSbb4qMoYWA=\", key: \"MPm0ZIlk9|ADco64gjkJz2NwLm6SWHvW\"}'
my_data = json.JSONDecoder().decode(json_data)
print my_data

throw exption behinde:

Traceback (most recent call last):
  File "D:\Python27\project\demo\digSeo.py", line 4, in <module>
    my_data = json.JSONDecoder().decode(json_data)
  File "D:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

Upvotes: 0

Views: 237

Answers (2)

farzad
farzad

Reputation: 8855

The json module in Python standard library can work well, that's what a lot of people are using for their applications.

However these few lines of code that use this module have a small issue. The problem is that your sample data is not a valid JSON. The keys (text and key) should be quoted like this:

json_data = '{"text": \"tl4ZCTPzQD0k|rEuPwudrAfgBD3nxFIsSbb4qMoYWA=\", "key": \"MPm0ZIlk9|ADco64gjkJz2NwLm6SWHvW\"}'

Upvotes: 0

Lukas Graf
Lukas Graf

Reputation: 32660

Your json_data is not valid JSON.

In JSON, property names need to be in double quotes ("). Also, the double quotes terminating the string values don't need to be ecaped since you're already using single quotes (') for the string.

Example:

json_data = '{"text": "tl4ZCTPzQD0k|rEuPwudrAfgBD3nxFIsSbb4qMoYWA=", "key": "MPm0ZIlk9|ADco64gjkJz2NwLm6SWHvW"}'

Upvotes: 2

Related Questions