简体   繁体   English

jQuery-在脚本标签中解析JSON

[英]jQuery - Parsing JSON inside script tag

I tried to parse JSON string inside a script tag <script src='//remotehost/test.js'>{'1':'2'}</script> 我试图在脚本标签<script src='//remotehost/test.js'>{'1':'2'}</script>解析JSON字符串

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

But I get SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data error. 但是我SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data错误的SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data得到了SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data I checked http://api.jquery.com/jquery.parsejson/ and the result of $(dom).html() is listed as one of malformatted JSON string result. 我检查了http://api.jquery.com/jquery.parsejson/ ,并将$(dom).html()的结果列为$(dom).html()的JSON字符串结果之一。 How do I parse the JSON using jQuery? 如何使用jQuery解析JSON?

The issue is that it's not valid JSON. 问题在于它不是有效的JSON。 Valid JSON uses double quotes. 有效的JSON使用双引号。

Change your HTML to: 将您的HTML更改为:

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

{'1':'2'} is a JavaScript Object, not a correct JSON. {'1':'2'}是JavaScript对象,不是正确的JSON。

JSON format of Object is a String use Double quotation marks, like: '{"1": "2"}' JSON格式的Object是使用双引号引起来的String,例如: '{"1": "2"}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM