Python3: unable to import JSONDecodeError from json.decoder
Asked Answered
B

3

7

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

Beekeeper answered 23/6, 2017 at 5:57 Comment(5)
Is your file named json.py? Please provide full traceback.Autopsy
from json import JSONDecodeErrorStem
Strange, this works fine for me. Can you see what happens if you try from json import decoder; print(decoder.JSONDecodeError) ?Accipiter
In [8]: print(decoder.JSONDecodeError) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-8-bb2acb16c5bc> in <module>() ----> 1 print(decoder.JSONDecodeError) AttributeError: 'module' object has no attribute 'JSONDecodeError'Beekeeper
Attached screenshot alsoBeekeeper
G
21

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

JSONDecodeError class is available starting from 3.5.x.

Gwenngwenneth answered 23/6, 2017 at 6:37 Comment(1)
Indeed. And since JSONDecodeError inherits from ValueError it is best to catch the latter if you care about portability.Raker
L
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.

Leavis answered 23/6, 2017 at 7:46 Comment(0)
C
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.

Cassidy answered 23/6, 2017 at 6:8 Comment(2)
Can you clarify whether 'from json import JSONDecodeError' is right or wrong in python3 ?Beekeeper
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.Cassidy

© 2022 - 2024 — McMap. All rights reserved.