[英]Javascript parse JSON error, but works fine in validator
当我尝试解析此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有效。 怎么了
UPDATE
我使用快递服务器模拟不和谐服务器,因此它将Web挂钩发送到快递服务器,我使用req.body获得JSON。
发生这种情况是因为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
已经是一个对象,您无需再次解析它。
尝试解析已解析的对象将引发错误。
就像不使用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'))
})
(要么)
这是此问题的一些步骤。
您可以使用lodash解决此问题。
导入lodash并调用unescape()。
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.