6

I setup virtualenv using python 3.4.3 and tried to import JSONDecodeError from json.decoder

from json.decoder import JSONDecodeError (I think its valid in python3 ? But why not working for me ?) 

But it is not working. Only below is working:

from simplejson import JSONDecodeError

How I did ?

virtualenv venv --no-site-packages -p python3 
pip install ipython
ipython
from json.decoder import JSONDecodeError
ImportError: cannot import name 'JSONDecodeError'

enter image description here

user2349115
  • 1,288
  • 2
  • 17
  • 34
  • Is your file named `json.py`? Please provide full traceback. – Łukasz Rogalski Jun 23 '17 at 06:01
  • from json import JSONDecodeError – e4c5 Jun 23 '17 at 06:06
  • Strange, this works fine for me. Can you see what happens if you try `from json import decoder; print(decoder.JSONDecodeError)` ? – a p Jun 23 '17 at 06:06
  • In [8]: print(decoder.JSONDecodeError) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in () ----> 1 print(decoder.JSONDecodeError) AttributeError: 'module' object has no attribute 'JSONDecodeError' – user2349115 Jun 23 '17 at 06:07
  • Attached screenshot also – user2349115 Jun 23 '17 at 06:11

3 Answers3

18

According to 3.4.x docs, plain ValueError is raised when JSON decoding fails.

JSONDecodeError class is available starting from 3.5.x.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • 6
    Indeed. And since `JSONDecodeError` inherits from `ValueError` it is best to catch the latter if you care about portability. – llude Aug 01 '17 at 07:32
2

According to Docs from module json (Python version >= 3.5.0), Python which version < 3.5.0 does not support import statement like what you just did, but if you use Python(version>=3.5.0), your import statement is definitely correct.

EUPHORAY
  • 453
  • 6
  • 15
0

json is the version of simplejson that has been integrated into Python. They have since been developed separately and are not the same anymore. So they cannot necessarily be used interchangably.

See this answer for more details about the differences.

Sarien
  • 6,647
  • 6
  • 35
  • 55
  • Can you clarify whether 'from json import JSONDecodeError' is right or wrong in python3 ? – user2349115 Jun 23 '17 at 06:13
  • As mentioned in other answers it depends on the minor version. If your questioned isn't "Why does this work with simplejson but not with json?" then I misunderstood. – Sarien Jun 23 '17 at 08:59