1

I am using NodeJS, and the following JSON.parse is failing but I cant work out why:

> s[0]
'[["hands[0].session.buyin", "332"]]'
> JSON.parse(s[0]);
SyntaxError: Unexpected token 
    at Object.parse (native)
    at repl:1:6
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at 

The string in question has been loaded from a file. If I copy past the string into the console it works, so my suspicion is that it might be to do with the way the file is encoded, but I just cant work out what. JSON.parse's error messages are distinctly unhelpful.

5
  • that doesn't look like JSON. Commented Sep 24, 2013 at 17:38
  • You could try a JSON Lint service to make sure your JSON is valid. Commented Sep 24, 2013 at 17:38
  • 1
    s[0] looks like two-dimensional array, isn't it? Commented Sep 24, 2013 at 17:41
  • What does the line look like in the file? Can you paste the contents? Commented Sep 24, 2013 at 17:41
  • JSON.parse('[["hands[0].session.buyin", "332"]]') works as expected. Commented Sep 24, 2013 at 17:44

2 Answers 2

11

It seem that the String includes a Byte-Order Mark.

> s[0].charCodeAt(0).toString(16)
'feff'

You'll have to strip that out before JSON.parse() can manage the rest.

> JSON.parse(s[0].trim())
[ [ 'hands[0].session.buyin', '332' ] ]
Sign up to request clarification or add additional context in comments.

1 Comment

This precisely is the problem.
1

On Node v0.10.12's REPL, this works fine:

> var b = '[["hands[0].session.buyin", "332"]]';
undefined
> JSON.parse(b)
[ [ 'hands[0].session.buyin', '332' ] ]
> 

The string is a valid JSON representation of a 2D array.

What's your environment?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.