Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

django - How do I JSON serialize a Python dictionary?

I'm trying to make a Django function for JSON serializing something and returning it in an HttpResponse object.

def json_response(something):
    data = serializers.serialize("json", something)
    return HttpResponse(data)

I'm using it like this:

return json_response({ howdy : True })

But I get this error:

"bool" object has no attribute "_meta"

Any ideas?

EDIT: Here is the traceback:

http://dpaste.com/38786/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: Python now has its own json handler, simply use import json instead of using simplejson.


The Django serializers module is designed to serialize Django ORM objects. If you want to encode a regular Python dictionary you should use simplejson, which ships with Django in case you don't have it installed already.

import json

def json_response(something):
    return HttpResponse(json.dumps(something))

I'd suggest sending it back with an application/javascript Content-Type header (you could also use application/json but that will prevent you from debugging in your browser):

import json

def json_response(something):
    return HttpResponse(
        json.dumps(something),
        content_type = 'application/javascript; charset=utf8'
    )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...