snehanshu.js
snehanshu.js

Reputation: 167

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:

{
  "$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.

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.

Upvotes: 0

Views: 3384

Answers (2)

snehanshu.js
snehanshu.js

Reputation: 167

Replacing JSON.parse(schema.toString()) with JSON.parse(schema.toString().trim()) worked!

Upvotes: 3

Josh
Josh

Reputation: 25

It sounds like the JSON file may have a UTF8 BOM at the beginning. Try converting the file to UTF8 without a BOM.

Upvotes: 2

Related Questions