在處理JSON報文時,有時會遇到反斜杠字符,那么這到底是什么原因呢?
{ "name": "Tom", "address": "New York, USA", "hobbies": ["reading", "swimming", "playing games"] }
上面的JSON報文是不會有反斜杠的,但是下面的報文就會產生反斜杠:
{ "name": "Tom", "address": "New York, USA", "hobbies": ["reading", "swimming", "playing games"], "description": "Tom\"s favorite book is \"Harry Potter\"." }
可以看到,原本雙引號在JSON中用來作為字符串的標識符,但是當其中的字符串中也含有雙引號時,就會產生歧義。為了避免這種歧義,就需要在雙引號前加上反斜杠進行轉義,這樣就可以表示字符串中本身就有的雙引號了。
{ "name": "Tom", "address": "New York, USA", "hobbies": ["reading", "swimming", "playing games"], "description": "Tom\\"s favorite book is \\"Harry Potter\\"." }
因此,當我們在處理JSON報文時,如果字符串中包含特殊字符,就需要使用反斜杠進行轉義,防止解析出錯。
上一篇php table輸出