Photo by John Schnobrich on Unsplash程序員
引子
json
產品經理:老司機;苦逼程序員:我bash
老司機:Jason,來看下怎麼這個筆記在 APP 端有展現,在 PC,Mobile 端沒有展現筆跡;app
我:臥槽,不可能啊,都是同樣的處理啊;curl
老司機:那你看看,順便打開了 APP 和 PC 端的展現效果;測試
我:臥槽,還真是(問號中);ui
因而我低着頭思考着問題回到了工位,內心思考着,不可能啊,我記得修復過這個上課前添加筆跡的 bug 了,怎麼還會有呢?上一張圖表示我當時的狀態。url
start
spa
接下來就開始調試代碼,經過測試發現一些筆跡被過濾掉了,來看這段代碼3d
try { item.body = JSON.parse(item.body); } catch (e) { continue; }複製代碼
這段代碼會在 JSON.parse()
出錯的時候跳過一次循環,那麼咱們來打個斷點看看被過濾掉的筆跡爲何不能被 parse
。咱們看到 catch
的消息
SyntaxError: Unexpected token in JSON at position 196 at JSON.parse (<anonymous>) at ignoreNoise (eventlog.js:53) at eventlog.js:391 "error"複製代碼
分析
OK,這種報錯一看就是不符合 json
字符串的格式致使的,那麼咱們來看 196
的位置是什麼。
咱們看到像是一連串的空格,那究竟是什麼呢?
encodeURI(item.body[196])"%09"複製代碼
OK,咱們查到 %09
是 TAB
。那麼問題找到了,咱們只須要把 TAB
產生的輸入替換到就好了。那麼須要怎麼作呢?
const decodeBoby = decodeURI(encodeURI(item.body).replace(/%0A/g, '\\n').replace(/%09/g, '\\t').replace(/%0D/g, '\\r'));複製代碼
在上面的一行代碼中咱們看到 %0A
%0D
也被轉換了,那麼這個究竟是什麼須要被轉換呢?
緣由
在這本 JSON standard [1] 的文檔裏咱們能夠看到下面寫的。
A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON valuegrammar. The set of tokens includes six structural tokens, strings, numbers, and three literal name tokens.
The six structural tokens:
[ U+005B left square bracket
{ U+007B left curly bracket
] U+005D right square bracket
} U+007D right curly bracket: U+003A colon, U+002C commaThese are the three literal name tokens:
true U+0074 U+0072 U+0075 U+0065
false U+0066 U+0061 U+006C U+0073 U+0065
null U+006E U+0075 U+006C U+006C
Insignificant whitespace is allowed before or after any token. Whitespace is any sequence of one or more ofthe following code points: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), andspace (U+0020). Whitespace is not allowed within any token, except that space is allowed in strings.
重點看 Insignificant whitespace
這行,意思是什麼呢,Whitespace
是不容許出如今 任何的 token 中的,可是 space (U+0020)
是容許出如今字符串中的。Whitespace
主要包含那些呢,上面寫道 character tabulation (U+0009) (tab)
, line feed (U+000A) (換行符)
, carriage return (U+000D) (回車)
。
那麼緣由就是在這裏。ENJOY!
若是你喜歡這篇文章
請你關注 JasonXTalk
1:http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf