如何将JSON封装在括号中?

发布于 2024-10-05 22:13:36 字数 600 浏览 0 评论 0原文

我有这段代码:

objects = Event.objects.all()
i = 0
dict = {}
small_dict = {}
for o in objects:
    small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image}
    dict[str(i+1)] = small_dict
    small_dict = {}

return HttpResponse(
    simplejson.dumps(dict),
    content_type = 'application/javascript; charset=utf8'
)

它给了我这个:

{"1": {"url": "http://www.rte.ie/tv/crimecall/", "image": "http://img.rasset.ie/0002c8d0-250.jpg", "id": 2, "name": "Crimecall"}}

我如何进一步将其封装在 () 括号之间?因为如果没有它们,我在 php 中解析它们时会出错。

I have this code :

objects = Event.objects.all()
i = 0
dict = {}
small_dict = {}
for o in objects:
    small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image}
    dict[str(i+1)] = small_dict
    small_dict = {}

return HttpResponse(
    simplejson.dumps(dict),
    content_type = 'application/javascript; charset=utf8'
)

and it gives me this :

{"1": {"url": "http://www.rte.ie/tv/crimecall/", "image": "http://img.rasset.ie/0002c8d0-250.jpg", "id": 2, "name": "Crimecall"}}

How I can further encapsulate it between () parentheses ? Because without them I'm getting error when parsing them in php.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

a√萤火虫的光℡ 2024-10-12 22:13:36
  1. JSON 的 MIME 类型是“application/json”。
  2. 如果您在 PHP 中解析它时遇到问题,那么这是一个 PHP 问题。不要在服务器端添加括号,而是在 PHP 中解析字符串之前添加它们。我想你知道如何在 PHP 中连接,对吧?无论如何,我不明白你的问题是什么 - 你不使用 json_解码
  1. The MIME type of JSON is "application/json".
  2. If you have problems parsing it in PHP, then it's a PHP problem. Don't add parens on the server side, but rather add them before parsing the string in PHP. I guess you know how to concatenate in PHP, right? Anyway, I don't understand what your problem is - don't you use json_decode?
总攻大人 2024-10-12 22:13:36

你可以这样做,但现在在浏览器中看不到。如果这不是问题的话,代码如下:

callback = request.GET.get('callback', '')
objects = Event.objects.all()
i = 0
dict = {}
small_dict = {}
for o in objects:
    small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image}
    dict[str(i+1)] = small_dict
    small_dict = {}

response = simplejson.dumps(dict)
response = callback + '(' + response + ')';

return HttpResponse(response,
    mimetype ='application/json; charset=utf8')

You can do it this way, but it's not viewable in browser now. I'f that's not a problem, here's the code :

callback = request.GET.get('callback', '')
objects = Event.objects.all()
i = 0
dict = {}
small_dict = {}
for o in objects:
    small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image}
    dict[str(i+1)] = small_dict
    small_dict = {}

response = simplejson.dumps(dict)
response = callback + '(' + response + ')';

return HttpResponse(response,
    mimetype ='application/json; charset=utf8')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文