LoginSignup
6
7

More than 3 years have passed since last update.

JSON.parse()でSyntaxErrorが出続けるときの対策

Last updated at Posted at 2019-10-04

1. 状況

pythonから出力したjson文字列を変数としてhtmlに貼り付けして,JSON.parse()したのちDatatablesを利用しようとしたところ,jsonの構文に誤りがないにもかかわらず下記のエラーが出た.

Uncaught SyntaxError: Unexpected token  in JSON at position 3

今回はconsole.log()した時点で\u0008に相当する「」(←多分表示されない)が見えたが,特殊文字の中にはconsole.log()で表示される特殊文字と出ないものがあるので注意する.

2.対策コード

stackoverflowに対策コードがあった.JSON.parse()でjsonの構文に誤りがないのにエラーが出る場合,とりあえずこれ貼っておけば良さそう.

// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")  
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");

// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,""); 

3.参考

https://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
https://qiita.com/qwq00/items/9cd8b8e095bea0633a88

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7