Issue
When I use json.loads in Python 3 and catch any resulting errors, like:
try:
data = json.loads(string)
except ValueError as err:
print(err)
I get a helpful message like:
Expecting ',' delimiter: line 12 column 12 (char 271)
I would like to be able to display this to the user, along with exactly the location which is causing the problem (I am reading in user-written JSON). How can I get out the line and column?
I could use a regex on err, but that feels like a bad idea, as I don't know if this message is internationalised, and could change in different versions of python. Is there a better way?
Solution
In Python 3.5 and up, a specialized JSONDecodeError
will be raised instead of ValueError
. It has several useful attributes - quoting from the documentation:
msg
: The unformatted error message.
doc
: The JSON document being parsed.
pos
: The start index ofdoc
where parsing failed.
lineno
: The line corresponding topos
.
colno
: The column corresponding topos
.
Answered By - Karl Knechtel Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.