如果数据包含URL, Javascript将无法解析JSON

Javascript cannot parsing JSON if the data contains some URL

本文关键字:JSON Javascript 数据包 URL 如果      更新时间:2023-09-26

有一个有效的JSON:

{"name":"tono","html":"<p><a href='"http:'/'/someurl.com'">Here<'/a> is the link<'/p>"}  

但是,当我通过javascript解析它时(我使用firefox的控制台)

JSON.parse('{"name":"tono","html":"<p><a href='"http:'/'/someurl.com'">Here<'/a> is the link<'/p>"}');

我得到这个错误

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 36 of the JSON data

这是一种预期行为吗?如何正确解析包含URL的JSON ?

只是为了获得额外的信息,这个是有效的:

JSON.parse('{"name":"tono","html":"<p><a href=>Here<'/a> is the link<'/p>"}');
Object { name: "tono", html: "<p><a href=>Here</a> is the link</p>" }

更多附加信息:

JSON在这里被完美解析:http://jsonviewer.stack.hu

转义字符串文本中的反斜杠,以便按字面意思处理。

console.log(JSON.parse('{"name":"tono","html":"<p><a href=''"http:''/''/someurl.com''">Here<''/a> is the link<''/p>"}'));

正斜杠转义的原因在这里解释:为什么正斜杠转义?

正如Barmar解释的那样,您可以像这样转义反斜杠。

JSON.parse('{"name":"tono","html":"<p><a href=''"http://someurl.com''">Here</a> is the link</p>"}');