【问题标题】:JSON to JS with Django: SyntaxError: missing : after property id带有 Django 的 JSON 到 JS:SyntaxError: missing : after property id
【发布时间】:2016-03-24 16:25:22
【问题描述】:

我正在尝试将 JSON 文件放入脚本中。我似乎无法通过从文件系统提供它来获得它,所以我创建了一个视图,将 JSON 数据返回到页面,如下所示:

def graph(request, d):                  #d.data is the file in the database
    data = json.load(d.data)
    return render(request, 'temp/template.html', {'json': data})

在我的 JS 中:

var j = {{ json|safe }};

当我查看 JS 的源代码时,它以这种格式显示数据:

{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}

我读到的应该不是问题。我没有任何名为“id”的变量,但标题中的错误指向所提供的 JS 行。

为什么会这样?另外,如何在我的脚本中使用 JSON 中的对象?

【问题讨论】:

  • u'name' 在 JS 中无效。它应该没有你。
  • 那是因为 Django 返回一个 unicode 数组,你知道有什么方法可以将它解析成有效的 JS 或者让视图返回它吗?

标签: javascript python json django


【解决方案1】:

使用simplejson解决:

import simplejson as json

其他一切如上。这是因为内置的 json.dumps 返回一个 unicode 数组,如:

{u'people': [{u'name': u'steve'}, {u'name': u'dave'}]}

当使用 simplejson 时,这应该不是问题。

【讨论】:

  • 真的,不。 simplejson的输出和json一样,你的问题是你实际上没有调用json.dumps()
  • 我在转储方面遇到了不同的错误,例如 xyz is not serializable
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-14
  • 2023-03-27
相关资源
最近更新 更多