简体   繁体   中英

JSON.parse failing without reason

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.

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' ] ]

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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