2012-11-10 41 views
9

這不是關於如何管理或糾正錯誤的JSON,它是關於如何向用戶解釋錯誤在錯誤的JSON中的位置。解析錯誤的JSON,並能夠顯示錯誤的位置

有沒有辦法找出解析器失敗的JSON中哪個位置。

我想在node.js應用程序中解決這個問題,所以如果可能的話請保留你的答案。

當我使用內置的JSON對象和錯誤的JSON的解析方法時,我只能得到異常消息SyntaxError: Unexpected string。我想知道錯誤發生在哪裏。

首選的是JSON.validate(json),返回結果ok/error和錯誤位置。事情是這樣的:

var faultyJsonToParse = '{"string":"value", "boolean": true"}'; 
var result = JSON.validate(faultyJsonToParse); 
if (result.ok == true) { 
    console.log('Good JSON, well done!'); 
} else { 
    console.log('The validator found a \'' + result.error + '\' of type \'' + result.errorType + '\' in your JSON near position ' + result.position); 
} 

的那受通緝的結果,上面會:

The validator found a 'SyntaxError' of type 'Unexpected string' in your JSON near position 35. 
+0

你期待的指數爲縮小的JSON字符串,其中出現錯誤? – Aesthete

+0

是的,類似的東西。我猜也可能是一個大JSON中的問題路徑。 – javabeangrinder

+0

葉..也許有讀通過這.. https://bugzilla.mozilla.org/show_bug.cgi?id=507998它可能不會回答你的問題,但可能給一些洞察,爲什麼這個功能不本地存在。 – Aesthete

回答

13

嘗試jsonLint

var faultyJsonToParse = '{"string":"value", "boolean": true"}'; 

try { 
    jsonlint.parse(faultyJsonToParse) 
} catch(e) { 
    document.write('<pre>' + e) 
} 

結果:

Error: Parse error on line 1: 
...ue", "boolean": true"} 
-----------------------^ 
Expecting 'EOF', '}', ',', ']', got 'undefined' 

(雖然jsonLint爲節點的項目,也可以在網絡中使用:簡單地抓取https://github.com/zaach/jsonlint/blob/master/web/jsonlint.js

正如@ EH9建議,圍繞標準json解析器創建一個包裝來提供詳細的異常信息是有意義的:

JSON._parse = JSON.parse 
JSON.parse = function (json) { 
    try { 
     return JSON._parse(json) 
    } catch(e) { 
     jsonlint.parse(json) 
    } 
} 

JSON.parse(someJson) // either a valid object, or an meaningful exception 
2

內置的JSON.parse()版本沒有一致的行爲。當論證是完整的時候是一致的,如果不是一致的話就是不一致的。這可以追溯到原始JSON庫實現中這個函數的不完整規範。該規範是不完整的,因爲它沒有定義異常對象的接口。這種情況直接導致你的問題。

雖然我現在還不知道現成的解決方案,但該解決方案需要編寫JSON解析器並跟蹤錯誤處理的位置信息。 (1)首先調用本地版本,然後(2)如果本地版本拋出異常,調用位置感知版本(它會更慢),讓它拋出異常你自己的代碼標準化。

1

如果您使用NodeJS,clarinet是一個非常好的基於事件的JSON解析器,它將幫助您生成更好的錯誤消息(行和列或錯誤)。 我建立使用clarinet's parser一個小工具,返回:

snippet (string): the actual line where the error happened 
line (number) : the line number of the error 
column (number) : the column number of the error 
message (string): the parser's error message 

的代碼是在這裏:https://gist.github.com/davidrapin/93eec270153d90581097