Ravi Teja
Ravi Teja

Reputation: 43

Parsing value from JSON string fails

I'm trying to extract the value of entry from below string. I tried to parse the string with json.loads() but it doesn't work. Instead, I receive below error message.

This is the string:

output = '336,{"token":"eyJhbGc.iOiJIUzI18_YREPr50","entry":"961156ef-2a9","project":"86a8e55a-9160","tenant":["73426ca1-bde"]}'

This is my code:

entry_id = json.loads(output)["entry"]

This is the error message:

 File "C:\Python27\lib\json\__init__.py", line 339, in loads
   return _default_decoder.decode(s)
 File "C:\Python27\lib\json\decoder.py", line 367, in decode
   raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 4 - line 1 column 341 (char 3 - 340)

What can I do to fix this?

Upvotes: 0

Views: 203

Answers (2)

moooeeeep
moooeeeep

Reputation: 32542

Only the {...}-part is the JSON object you can extract that value from. You need to split the string before you parse. (You should add the optional maxsplit argument to only split on the first comma.)

Example:

x, s = output.split(',', 1)
entry_id = json.loads(s)["entry"]

The number before that comma is in itself a valid JSON value, but comma separated values are only allowed inside JSON arrays [...] or JSON objects {...}. The error message therefore indicates, that there is extra data in the input string that doesn't belong there. Therefore you need to strip the value before you can parse the object contained in the remainder of the string.

For reference:

Upvotes: 1

Ravi Teja
Ravi Teja

Reputation: 43

First remove the first 4 characters to get a valid JSON string and then use json.loads() to get value from JSON string.

# remove first four characters
line = output[4:]
# parse a value from json to get id
entry_id = json.loads(line)["entry"]
print entry

Output:

961156ef-2a9

Upvotes: 0

Related Questions