jQuery - 解析脚本标记中的 JSON

jQuery - Parsing JSON inside script tag

本文关键字:JSON 脚本 jQuery      更新时间:2023-09-26

我试图解析脚本标记中的 JSON 字符串<script src='//remotehost/test.js'>{'1':'2'}</script>

dom = document.scripts[document.scripts.length - 1]; //it gets the correct tag, checked
d = $.parseJSON($(dom).html());

但我得到SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data错误。我检查了 http://api.jquery.com/jquery.parsejson/,$(dom).html()的结果被列为格式错误的 JSON 字符串结果之一。如何使用jQuery解析JSON?

问题是它不是有效的 JSON。 有效的 JSON 使用双引号。

将您的 HTML 更改为:

<script src='//remotehost/test.js'>{"1":"2"}</script>

{'1':'2'}是一个JavaScript对象,而不是正确的JSON。

对象的 JSON 格式是使用双引号的字符串,例如:'{"1": "2"}'