Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何解析带有HTML标记的字符串?_Javascript_Html_Json - Fatal编程技术网

Javascript 如何解析带有HTML标记的字符串?

Javascript 如何解析带有HTML标记的字符串?,javascript,html,json,Javascript,Html,Json,我有这样一个字符串: var s = '{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}'; var obj = JSON.parse(s);

我有这样一个字符串:

var s = '{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}';
var obj = JSON.parse(s);
{“限制”:“}
但是我不能用JSON.parse解析它。我的代码如下所示:

var s = '{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}';
var obj = JSON.parse(s);

要解析这些html属性,您需要双重转义引号:
\\“因为它们位于两层之下。或者,最好使用单引号作为属性。

您可以使用
替换

var s = '{"Restriction":"<wbr><a href=\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\" target=\"_blank\"><span style=\"color: rgb(0, 0, 205);\">more info</span></a></wbr>"}';
console.log(s);
console.log(s.replace(/\"/g, ""));
var s='{“限制”:“}”;
控制台日志;
console.log(s.replace(/\“/g,”);

它不是有效的JSON。反斜杠也应该避免

var s = '{"Restriction":"<wbr><a href=\\"https://www.google.com.tw/#q=%E4%B8%AD%E5%9C%8B\\" target=\\"_blank\\"><span style=\\"color: rgb(0, 0, 205);\\">more info</span></a></wbr>"}';
JSON.parse(s); // correct
var s='{“限制”:“}”;
JSON.parse(s);//对的

我认为,您应该将错误报告发布到这个
远程API

您无法解析数据块,您需要加载所有数据

  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      var json = '';
      res.on('data', function (chunk) {
        // Why this arg called chunk? That's not all data yet
        json += chunk;
      });
      res.on('end', function(){
         // Here we get it all
         console.log(JSON.parse(json));
      });

  });

我是通过调用一个远程API获得它的
。这怎么可能是真理?我认为,您是复制粘贴的API答案,并在代码中按原样使用。。您的字符串实际上没有反斜杠,
replace
无法在此提供帮助。