2013-04-23 85 views
0

我想解析一些我從第三方API接收到的JSON。問題是,一些JSON的有引號內引號,像這樣:解析JSON中的雙引號

var json = '{"sentence": "My favorite sport is "dodgeball"." }'; 

我敢肯定的瀏覽器解釋引號作爲

"My favorite sport is" 

,然後擊中了一個語法錯誤以下字符。我如何避免這種情況?

編輯:我張貼的問題的一個簡化版本,但這裏是那是給我找麻煩的實際代碼片斷(這個問題是「酷廠商」裹在引號):

{"content":"Vana Workforce is the Cloud HR Company. We are a global provider of human capital software and service solutions specifically designed to the needs of small and medium enterprises delivered on-demand. 

Developed on the industry's leading cloud platform Force.com, Vana Human Capital Management delivers one complete and integrated human capital management solution for global organizations form hire to retire including the core human resource system of record, benefits & compensation, absence management, performance and talent management, career and succession planning, workforce collaboration, and workforce analytics. 

Founded in 2008, Vana Workforce has offices in Canada and the United States with customers on every continent, and was recently recognized by Gartner Research as a "Cool Vendor" for 2010.","val":"Description"} 
+1

這JSON是無效的。他到底是從API獲取它的? – Pointy 2013-04-23 21:04:50

+0

我拉用戶的列表,短生物部分有時包含雙引號。可悲的是,該服務(zoho.com)並未對其進行消毒。 – 2013-04-23 21:09:54

+0

這不是「消毒」問題;這只是錯誤的。如果您將它提供給JSON解析器,換句話說,它只會引發異常。既然你沒有這樣做,那麼你在做什麼? – Pointy 2013-04-23 21:30:18

回答

2

這不是有效的JSON,所以你不能用標準方法來做到這一點。

您可能已逃離這樣的語錄:"sport is \" "否則你需要編寫自己的消毒劑

+0

我將如何清理代碼(僅轉義值內的字符)? – 2013-04-23 21:03:11

+0

你將不得不檢查字符串,如果你看到一個模式替換「與\」。如果這是隨機發生的,那麼我認爲你不能自動執行它,你需要手動清理它(或修復爲你提供的僞json服務) – Kenneth 2013-04-23 21:05:14

+1

@jarednielsen你不能真正消毒它;它在語法上不正確。它應該由創建它的服務首先正確地生成。 – Pointy 2013-04-23 21:05:46

1

這些報價應逃脫 -

"My favorite sport is \"dodgeball\"." 

如果它是一個真正的服務(不做作業),這將是正確完成。如果它是作業,那就去修復服務中的錯誤。

+0

我該怎麼做呢?真正的JSON響應非常長,我不能手動轉義每一個引用。 – 2013-04-23 21:01:51

+2

@jarednielsen如果服務實際上以這種方式被破壞,那就不要使用它。 – djechlin 2013-04-23 21:03:04

+0

好的。會使用XML避免這個問題? – 2013-04-23 21:03:28