2010-11-06 123 views
2

據說這裏:在JSON字符串轉義字符

的JSON內的任何報價必須 「逃逸」與前一個反斜槓。 否則,JavaScript會混淆 我們想要顯示哪些引號 以及哪些引號是 編程的一部分。

但在他們的代碼片段中我看不到任何轉義字符是這個教程越野車我很困惑? :

var movielisttext = "{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}"; 

我的問題是特別是如果他們的文章有錯誤或沒有,因爲它讓我吃驚初學者教程可以嵌入這樣的錯誤。

+0

http://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response – 2010-11-06 16:48:03

回答

3

你有什麼是JavaScript,而不是JSON。

如果你想JSON:

{ 
    "movielist": [ 
     "Friday the 13th", 
     "Friday the 13th Part 2", 
     "Friday the 13th Part III", 
     "Friday the 13th: The Final Chapter", 
     "Friday the 13th: A New Beginning" 
    ] 
} 

如果你想有一個JavaScript對象

var movielisttext = { 
     "movielist": [ 
      "Friday the 13th", 
      "Friday the 13th Part 2", 
      "Friday the 13th Part III", 
      "Friday the 13th: The Final Chapter", 
      "Friday the 13th: A New Beginning" 
     ] 
    }; 

如果你想包含JSON一個JavaScript字符串:

var movielisttext = '{"movielist": ["Friday the 13th","Friday the 13th Part 2","Friday the 13th Part III","Friday the 13th: The Final Chapter","Friday the 13th: A New Beginning"]}'; 

var movielisttext = "{\"movielist\": [\"Friday the 13th\",\"Friday the 13th Part 2\",\"Friday the 13th Part III\",\"Friday the 13th: The Final Chapter\",\"Friday the 13th: A New Beginning\"]}"; 

由於數據本身不包含任何"字符,因此就JSON而言,不需要轉義它們。

+0

如果數據本身包含「和」,那該怎麼辦? – user310291 2010-11-06 18:14:00

+0

如果數據包含「」字符,那麼它們將需要逃脫。 '''不會因爲它們不是分隔符。如果你想在JS中使用它作爲一個字符串(按照最後一個例子),那麼你需要(再次)轉義引號和(JSON)轉義序列。 – Quentin 2010-11-06 18:30:47

2

由於這是JavaScript和不JSON,只是省略了周圍的引號:在JSON

var movielisttext = {"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}; 
1

字符串必須始終用雙引號包裹。在那個例子中,他們應該已經格式化了JSON是這樣的:

var movielisttext = '{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}'; 

但是,如果他們的意圖是要建立一個字面Javascript對象,他們應該使用:

var movielisttext = {"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}; 

在第一種情況下,值的movielisttext是一個字符串,在第二種情況下它是一個對象

1
var movielisttext = '{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}'; 

OR

var movielisttext = "{\"movielist\": [\"Friday the 13th\", \"Friday the 13th Part 2\", \"Friday the 13th Part III\", \"Friday the 13th: The Final Chapter\", \"Friday the 13th: A New Beginning\"]}"; 

會做的伎倆。