2016-04-27 150 views
1

舊的出錯信息包含在雙引號期待物業名稱: 我得到這個錯誤:ValueError異常:在Python

ValueError: Expecting property name enclosed in double quotes:

這是我的代碼。我想字符串轉換ResultPart在字典:

resultPart = '{"sentences": [{"parsetree": [], [("words": "Q", {"Lemma": "q", "NamedEntityTag": "O", "CharacterOffsetEnd": "1", "PartOfSpeech": "NN", "CharacterOffsetBegin": "0"})], "dependencies": [], "text": "Q", "parsetree": [], "indexeddependencies": []}]}' 
resultPart2 = json.dumps(resultPart) 
#result should be a dict 
result = json.loads(resultPart) 

編輯:我糾正了一部分,現在我已經此錯誤:

TypeError: string indices must be integers

這是新代碼:

resultPart = "{'sentences': [{'words': [('Q', {'Lemma': 'q', 'NamedEntityTag': 'O', 'CharacterOffsetEnd': '1', 'PartOfSpeech': 'NN', 'CharacterOffsetBegin': '0'})], 'dependencies': [], 'text': 'Q', 'parsetree': [], 'indexeddependencies': []}]}" 
resultPart2 = json.dumps(resultPart) 
result = json.loads(resultPart2) 
+3

你似乎有一個'('在那裏我期望一個''{ 。你爲什麼手工創建JSON? – jonrsharpe

回答

1

該問題似乎在以下行:

{ 
... 
    "parsetree": [], [ 
    "words": "Q", { 
     "Lemma": "q", 
     "NamedEntityTag": "O", 
     "CharacterOffsetEnd": "1", 
     "PartOfSpeech": "NN", 
     "CharacterOffsetBegin": "0" 
    }], 
... 

} 

[]作爲"parsetree"的值後正在尋找另一個key。所以它需要像下面這樣是有效的JSON。

{ 
... 
    "parsetree": [], 
    "more_words": [ 
    "words": "Q", { 
     "Lemma": "q", 
     "NamedEntityTag": "O", 
     "CharacterOffsetEnd": "1", 
     "PartOfSpeech": "NN", 
     "CharacterOffsetBegin": "0" 
    }], 
... 

} 
0

這與錯誤無關,但會有所幫助。

您正在將字符串轉儲爲另一個字符串作爲JSON ...這將導致轉義字符。

>>> s = '{"dependencies": [], "sentences": [{"parsetree": []}], "text": "Q"}' 
>>> import json 
>>> json.dumps(s) 
'"{\\"dependencies\\": [], \\"sentences\\": [{\\"parsetree\\": []}], \\"text\\": \\"Q\\"}"' 

我非常懷疑這是你想要的。話雖這麼說,做一個Python字典,而不是因爲:1)它是容易出錯少,2)你可以得到正確的JSON

>>> s = {1: 2, 'sentences': [{'parsetree': []}], 'dependencies': [], 'text': "Q"} 
>>> json.dumps(s) 
'{"1": 2, "dependencies": [], "sentences": [{"parsetree": []}], "text": "Q"}'