最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Django json single and double quotes? - Stack Overflow

programmeradmin0浏览0评论

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'}]"

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'}]"

Share edited Apr 12, 2012 at 2:42 Derek asked Apr 12, 2012 at 1:57 DerekDerek 12.4k31 gold badges106 silver badges166 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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).

发布评论

评论列表(0)

  1. 暂无评论