[英]How to parse HTML string using JSON.parse() in JavaScript?
[英]How do I JSON.parse a string with HTML tag?
我有一個像這樣的字符串:
{"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);
我收到了錯誤:
未捕獲的SyntaxError:意外的令牌。
我的猜測是“\\”出錯了,但我無法更改字符串,因為我是通過調用遠程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));
});
});
要解析這些html屬性,您需要雙重轉義引號: \\\\“因為它們是兩層向下。或者,最好是,可以使用單引號作為屬性。
您可以使用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, ""));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.