在JSON字符串转义字符

问题描述:

据说这里:在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://*.com/questions/2275359/jquery-single-quote-in-json-response – 2010-11-06 16:48:03

你有什么是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

由于这是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"]}; 

字符串必须始终用双引号包裹。在那个例子中,他们应该已经格式化了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是一个字符串,在第二种情况下它是一个对象

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\"]}"; 

会做的伎俩。