kag359six
kag359six

Reputation: 2253

Dict type throws error in json.dumps

I am passing a dictionary to json.dumps and it is still throwing an error:

TypeError: Undefined is not json serializable

I even check the type before calling the function to make sure it is a dictionary type.I'm using the Flask microframework and trying to return a Response object containing really simple json to an ajax request:

$(document).ready(function() {

$.getJSON($SCRIPT_ROOT + '/getDictionary', function(data) {

    console.log(data);

});

});

@app.route('/getDictionary')

def getDictionary():

    empty_dic = {'empty' : 'dict'}

    if type(empty_dic) is dict:
        return Response(json.dumps(empty_dic), mimetype = "application/json")

Upvotes: 0

Views: 2978

Answers (4)

skar
skar

Reputation: 401

Are you trying this by any chance

json.dumps(emptydic, encoding='utf-8')

I am trying this on Python 2.7 and the string object will not have an attribute called encoded.

Upvotes: 0

Dave Lasley
Dave Lasley

Reputation: 6242

Your capitalization is off, note you define emptydic but try to serialize emptyDic. Try this:

empty_dict = {'simple' : 'dict'}

if type(empty_dict) is dict:
    return Response(json.dumps(empty_dict).encoded('utf8'), mimetype = "application/json")

Note it's also against PEP8 to use camel case for variables. Snake case is recommended

Upvotes: 1

jedwards
jedwards

Reputation: 30200

Here's an example that works:

import json

emptydic = {'simple' : 'dict'}

if isinstance(emptydic, dict):    # Note capitalization
    print(json.dumps(emptydic))   # {"simple": "dict"}

The type checking condition has changed slightly, and I stripped the Response/mimetype stuff, because it seems orthogonal to your issue.

Upvotes: 1

Sean Saito
Sean Saito

Reputation: 675

Your dictionary has name "emptydic"

In the condition, you use "emptyDic"

Try:

emptyDic = {"simple": "dict"}

if type(emptyDic) is dict:
    return Response(json.dumps(emptyDic).encoded('utf8'), mimetype = "application/json")

Upvotes: 0

Related Questions