steve254 steve254 - 25 days ago 9
JSON Question

Dumping data structure to JSON in Python raises unorderable types str and builtin_function_or_method

I'm trying to call Flask's

jsonify
on a data structure, but I get
TypeError: unorderable types: str() < builtin_function_or_method()
. How do I fix this error?

bucketlists = [{
'id': 1,
'name': "BucketList1",
'items': [{
id: 1,
'name': "I need to do X",
'date_created': "2015-08-12 11:57:23",
'date_modified': "2015-08-12 11:57:23",
'done': False
}],
'date_created': "2015-08-12 11:57:23",
'date_modified': "2015-08-12 11:57:23",
'created_by': "1113456"
}]

@app.route('/bucketlists/', methods=['GET'])
def get_bucketlists():
return jsonify({'bucketlists': bucketlists})

Answer

id is a builtin Python function; jsonify cannot serialize it, you need to wrap the dictionary key with quotes to make it a string:

bucketlists = [{
    'id': 1,
    'name': "BucketList1",
    'items': [{
        'id': 1, # -----> Here
        'name': "I need to do X",
        'date_created': "2015-08-12 11:57:23",
        'date_modified': "2015-08-12 11:57:23",
        'done': False
    }],
    'date_created': "2015-08-12 11:57:23",
    'date_modified': "2015-08-12 11:57:23",
    'created_by': "1113456"
}]

Additionally, you need to add double underscores to access the name of the module :

app = Flask(__name__)
Comments