当我尝试解析此JSON(Discord webhook)时:
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "",
"value": "some of these properties have certain limits..."
},
{
"name": "",
"value": "try exceeding some of them!"
},
{
"name": "",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
使用此代码:
var parsed = JSON.parse(req.body)
我收到此错误:
SyntaxError: Unexpected token o in JSON at position 1
但是如果我使用
这样的网站https://jsonformatter.curiousconcept.com
要验证JSON,它表示JSON有效。 怎么了?
更新
我使用快递服务器来模拟不和谐服务器,因此它将Web挂钩发送到快递服务器,我使用req.body获取JSON。
答案 0 :(得分:1)
之所以会发生这种情况,是因为JSON
是一个全局对象(与读取方法parse
的对象相同),因此,当您调用JSON.parse(JSON)
时,javascript会认为您要解析它。
将变量传递给验证器时不会发生相同的事情,因为它将被分配给局部变量:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
编辑
根据您更新的问题,可能是因为您已经使用bodyParser.json()
作为中间件,并且当您使用它时,req.body
已经是一个对象,不需要再次解析它。
尝试解析已解析的对象将引发错误。
答案 1 :(得分:0)
就像不使用JSONStream一样:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
要与JSONStream一起使用,将类似于:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
这是解决此问题的一些步骤。
您可以使用lodash解决此问题。
导入lodash并调用unescape()。
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);