我有这样一个字符串:
{"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);
我得到了错误:
Uncaught SyntaxError: Unexpected token.
我猜是「\"」弄错了,但我无法更改字符串,因为我是通过调用远程 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
我认为,您应该向此远程API
发布错误报告。
关于javascript - 我如何 JSON.parse 带有 HTML 标签的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595331/