如何用HTML标记JSON.parse字符串
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);
我得到了错误:
未捕获的语法错误:意外的标记。
我的猜测是"''"出错了,但我无法更改字符串,因为我是从对远程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属性,您需要对引号进行双转义:''''",因为它们向下两层。或者,最好为属性使用单引号。
相关文章:
- 在JSON.parse Javascript中字符串化Java对象抛出错误
- 停止JSON.parse()从JSON字符串数据中删除尾随零
- 如何避免JSON.stringify在特殊情况下返回undefined,从而为JSON.parse创建字符串失败
- 想要将 JSON 字符串传递给 javascript 变量 [ JSON.parse(),eval()] 对我不起作用,
- 使用 JSON.parse 将字符串(变量)转换为对象,错误意外标记
- “JSON.parse(str)”返回“意外令牌c”,但str是一个字符串
- 如何使用API URL的JSON.parse将JSON字符串更改为Javascript对象
- d3.csv.parse只解析csv字符串的第一行
- 试图执行JSON.parse,但它不喜欢我使用服务器返回的字符串所做的操作
- Parse的javascript CloudCode对httprequest的字符串操作添加了额外的反斜杠
- Parse.com / Javascript - 将用户对象ID字符串保存为用户指针
- 复制和粘贴带有转义引号的字符串化对象时的 JSON.parse 异常
- 需要 Date.parse 以外的方法来解析日期字符串
- JSON.parse 不适用于从 AJAX 调用返回的 JSON 字符串
- 具有意外令牌的 JSON.parse 字符串
- Node.js JSON.parse(字符串)正在返回一个字符串
- JSON.parse字符串-意外的令牌
- 如何用HTML标记JSON.parse字符串
- JavaScript json.parse字符串错误
- AngularJS$parse字符串到“控制器作为”方法