PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

[FIXED] How to get error location from json.loads in Python

 July 25, 2022     json, python     No comments   

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 of doc where parsing failed.
lineno: The line corresponding to pos.
colno: The column corresponding to pos.



Answered By - Karl Knechtel
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing