简体   繁体   English

Javascript解析JSON错误,但在验证器中工作正常

[英]Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook): 当我尝试解析此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
      }
    ]
  }
}

Using this code: 使用此代码:

var parsed = JSON.parse(req.body)

I get this error: 我收到此错误:

SyntaxError: Unexpected token o in JSON at position 1

But if I use a website such as 但是如果我使用诸如

https://jsonformatter.curiousconcept.com https://jsonformatter.curiousconcept.com

To validate the JSON, it says the JSON is valid. 为了验证JSON,它表示JSON有效。 What is wrong here? 怎么了

UPDATE UPDATE

I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body. 我使用快递服务器模拟不和谐服务器,因此它将Web挂钩发送到快递服务器,我使用req.body获得JSON。

This happens because JSON is a global object (it's the same object where you read the method parse !), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it. 发生这种情况是因为JSON是一个全局对象(与您读取方法parse对象相同),因此,当您调用JSON.parse(JSON) javascript认为您想对其进行解析。

The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable: 将变量传递给验证器时,不会发生相同的事情,因为它将被分配给局部变量:

let JSON = "{}";

validate(JSON);

function(x) {
JSON.parse(x); // here JSON is again your global object!
}

EDIT 编辑

According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again. 根据您更新的问题,可能是因为您已经使用bodyParser.json()作为中间件,并且当您使用它时, req.body已经是一个对象,您无需再次解析它。

Trying to parsing an already parsed object will throw an error. 尝试解析已解析的对象将引发错误。

It would be something like without using JSONStream: 就像不使用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())
    })
})

For using it with JSONStream, it would be something like: 对于将它与JSONStream一起使用,它将类似于:

http.request(options, function(res) {
  var stream = JSONStream.parse('*')
  res.pipe(stream)
  stream.on('data', console.log.bind(console, 'an item'))
})

(OR) (要么)

Here is the Some Steps for this issue.. 这是此问题的一些步骤。

You Can use lodash for resolving this. 您可以使用lodash解决此问题。

import the lodash and call unescape(). 导入lodash并调用unescape()。

const _ = require('lodash');

let htmlDecoder = function(encodedStr){
    return _.unescape(encodedStr);
}

htmlDecoder(JSON);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM