简体   繁体   English

JSON中位置0处的意外令牌与Node.js中的有效JSON一起发生

[英]Unexpected token in JSON at position 0 happening with valid JSON in Node.js

I have a file called HeartbeatResponse_v1p0.json whose contents are as follows: 我有一个名为HeartbeatResponse_v1p0.json的文件,其内容如下:

{
  "$schema": "http://json-schema.org/draft-06/schema#",
  "$id": "urn:OCPP:Cp:2:2018:4:HeartbeatResponse",
  "comment": "OCPP 2.0 - v1p0",
  "type": "object",
  "additionalProperties": true,
  "properties": {
    "currentTime": {
      "type": "string",
      "format": "date-time"
    }
  },
  "required": [
    "currentTime"
  ]
}

Now in index.js , I am trying to JSON.parse it. 现在在index.js ,我正在尝试JSON.parse

const fs = require('fs')
var schema = fs.readFileSync('./HeartbeatResponse_v1p0.json')
console.log(JSON.parse(schema.toString()))

But I get the following error: 但是我收到以下错误:

undefined:1
{
^
SyntaxError: Unexpected token  in JSON at position 0
    at JSON.parse (<anonymous>)
    .........

I have no idea why this is happening. 我不知道为什么会这样。 Please help me. 请帮我。

JSON.parse(schema.toString().trim())替换JSON.parse(schema.toString()) JSON.parse(schema.toString().trim())

It sounds like the JSON file may have a UTF8 BOM at the beginning. 听起来JSON文件的开头可能带有UTF8 BOM。 Try converting the file to UTF8 without a BOM. 尝试将文件转换为不带BOM的UTF8。

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

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