【问题标题】:Error parsing json content through JSON.parse()通过 JSON.parse() 解析 json 内容时出错
【发布时间】:2020-05-12 12:42:48
【问题描述】:

我正在使用 django 的 json_script 模板标签从上下文视图中获取 json。

我收到这样的 json

{{rules|json_script:"rules"}}

<script lang="javascript">
    const rules = JSON.parse($('#rules').text())
</script>

这是我从{{rules|json_script:"rules"}}收到的信息

<script id="rules" type="application/json">{"id": 10, "string": "demo", "profile": "Alumno Demo", "license": "Licencia no facturable por usuario demo", "field": "codigo_usuario", "include": true, "order": 1, "uppercase_sensitive": false, "dateadded": "2020-05-11T08:06:35Z", "billable": false}</script>

但是当我尝试 JSON.parse 时,我收到了这个错误:

VM760:5 Uncaught SyntaxError: Unexpected token R in JSON at position 5

我做错了什么?如果我复制脚本的内容,它似乎是一个正确的 json。

提前致谢!

【问题讨论】:

  • 你能console.log($('#rules').text()) 并发布输出吗?

标签: javascript json django


【解决方案1】:

实际上 $('#rules').text() 正在返回一个 jQuery n.fn.init 函数。

看jQuery库的代码:

`var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};`

如果在 DOM 上找不到元素,它会返回一个空函数。

你可以做什么:

1。像这样使用基本的javascript方法getElementsByTagName:

document.getElementsByTagName('script')

这将返回一个脚本元素数组,在您的情况下,您将获得 2 个元素,并且只需使用 text 属性来获取脚本标签内容。

JSON.parse(document.getElementsByTagName('script')[0].text)

2。您还可以在脚本中声明一个变量并像这样解析 JSON:

var stringifiedJson = {"id": 10, "string": "demo", "profile": "Alumno Demo", "license": "Licencia no facturable por usuario demo", "field": "codigo_usuario", "include": true, "order": 1, "uppercase_sensitive": false, "dateadded": "2020-05-11T08:06:35Z", "billable": false}; JSON.parse(stringifiedJson);

【讨论】:

  • 你是对的,但我没有得到一件事:为什么如果我使用 getElementByIid 我得到:
    ...
    什么时候我得到使用 getElementsByTagName('script')[20].text 我得到
  • 只是因为scripts元素不能使用id属性,所以只能有async、charset、src、type、defer。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
相关资源
最近更新 更多