Reputation: 12378
I noticed that if you use the simplejson function in django all the strings are enclosed with single quotes, and the whole json object string is enclosed in double quotes. When I take this string and hand it in to JSON.parse, it gives me an error because they want to use single quotes to enclose the whole object and double quotes for the strings. I could switch them with javascript replace, but then I'd have to take into consideration cases like apostrophes, but I'm sure there is a better way. Is there a way to get django's simplejson to output the object string to the format of JSON.parse?
More info:
django view:
def view(request):
list = [{"a":"apple",},]
return HttpResponse(simplejson.dumps(str(list)), mimetype="application/json")
what the javascript string turn out to be
"[{'a': 'apple'}]"
Upvotes: 3
Views: 6144
Reputation: 23871
update
remove the str()
around list, simply simplejson.dumps(list)
. str()
trans the list to a string, thus you got "[{'a': 'apple'}]"
in client side.
Can you update the question to demo where simplejson encloses strings w/ single quotes?
django.utils.simplejson
, normally, conforms w/ JSON specification and does not use single quotes to wrap things. If you mean
>>> from django.utils.simplejson import dumps
>>> dumps("Hello")
'"Hello"' # single quotes here
>>> repr(dumps("Hello"))
'\'"Hello"\'' # or here
They're notations of Python, you don't want to directly use them in JSON.parse (the first one is OK though).
Upvotes: 5