javascript - Node.js 中的有效 JSON 发生位置 0 处 JSON 中的意外标记

标签 javascript json node.js jsonschema

我有一个名为 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"
  ]
}

现在在 index.js 中,我正在尝试 JSON.parse 它。

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

但我收到以下错误:

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

我不知道为什么会发生这种情况。请帮助我。

最佳答案

替换 JSON.parse(schema.toString())JSON.parse(schema.toString().trim())成功了!

关于javascript - Node.js 中的有效 JSON 发生位置 0 处 JSON 中的意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51853247/

相关文章:

javascript - Xpath 函数在剧作家中不起作用

node.js - 在Express中渲染jade时包含其他文件的内容吗?

javascript - Javascript 中 with 语句的 future

javascript - 如何使用 jQuery 从 JSON 读取文件?

json - 使用 jq 从每个主要节点版本获取最新版本

php - 如何使用 FOSRestBundle 以 JSON 格式返回或显示数据

javascript - node.js 中具有大数字的按位运算符

javascript - 如何使用特定 id 删除元素

JavaScript:这个计时器可靠吗?

javascript - 位置 4 的 JSON 中的意外标记 <