如何用HTML标记JSON.parse字符串

How do I JSON.parse a string with HTML tag?

本文关键字:parse 字符串 JSON 标记 何用 HTML      更新时间:2023-09-26

我有一个这样的字符串:

{"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解析它。我的代码如下:

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);

我得到了错误:

未捕获的语法错误:意外的标记。

我的猜测是"''"出错了,但我无法更改字符串,因为我是从对远程API的调用中获得的。下面是我的代码:

// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
function PostCode(codestring) {
  // An object of options to indicate where to post to
  var post_options = {
      host: 'api.domain',
      port: '80',
      path: '/webservice/service.asmx/method?key=123456',
      method: 'GET',
      headers: {
          'Content-Type': 'text/plain'
      }
  };
  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        var x = {};
          console.log('Response down');
          x = JSON.parse(chunk);
      });
  });
  post_req.end();
}
PostCode();

它不是一个有效的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

我认为,您应该向这个remote 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));
      });
  });

您可以使用replace:

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, ""));

要解析这些html属性,您需要对引号进行双转义:''''",因为它们向下两层。或者,最好为属性使用单引号。