Use the as statement. You can read more about this in Handling Exceptions.
>>> try:
... print(a)
... except NameError as e:
... print(dir(e)) # print attributes of e
...
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__traceback__', 'args',
'with_traceback']
Answer from Ashwini Chaudhary on Stack OverflowUse the as statement. You can read more about this in Handling Exceptions.
>>> try:
... print(a)
... except NameError as e:
... print(dir(e)) # print attributes of e
...
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__traceback__', 'args',
'with_traceback']
Here is an example from the docs:
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print 'My exception occurred, value:', e.value
I encountered another problem that returns the same error.
Single quote issue
I used a json string with single quotes :
{
'property': 1
}
But json.loads accepts only double quotes for json properties :
{
"property": 1
}
Final comma issue
json.loads doesn't accept a final comma:
{
"property": "text",
"property2": "text2",
}
Solution: ast to solve single quote and final comma issues
You can use ast (part of standard library for both Python 2 and 3) for this processing. Here is an example :
import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json
# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}
Using ast will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It's a pretty good and safely alternative of eval() function for literal structures.
Python documentation warned us of using large/complex string :
Warning It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.
json.dumps with single quotes
To use json.dumps with single quotes easily you can use this code:
import ast
import json
data = json.dumps(ast.literal_eval(json_data_single_quote))
ast documentation
ast Python 3 doc
ast Python 2 doc
Tool
If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.
json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:
>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'
So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.
So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?
Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.
I don't understand when each one will be raised, and I don't understand the online explanations