ValueError:在Python中,属性名称应包含在双引号中
旧错误: 我有一个错误: ValueError:应使用双引号括起属性名称: 这是我的密码。我想转换dict上的字符串ResultPart:ValueError:在Python中,属性名称应包含在双引号中,python,Python,旧错误: 我有一个错误: ValueError:应使用双引号括起属性名称: 这是我的密码。我想转换dict上的字符串ResultPart: resultPart = '{"sentences": [{"parsetree": [], [("words": "Q", {"Lemma": "q", "NamedEntityTag": "O", "CharacterOffsetEnd": "1", "PartOfSpeech": "NN", "CharacterOffsetBegin": "0"})
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:字符串索引必须是整数
这是新代码:
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)
问题似乎出现在以下行:
{
...
"parsetree": [], [
"words": "Q", {
"Lemma": "q",
"NamedEntityTag": "O",
"CharacterOffsetEnd": "1",
"PartOfSpeech": "NN",
"CharacterOffsetBegin": "0"
}],
...
}
它正在查找[]
后面的另一个键
,作为“parsetree”
的值。因此,要成为有效的JSON,它需要如下所示
{
...
"parsetree": [],
"more_words": [
"words": "Q", {
"Lemma": "q",
"NamedEntityTag": "O",
"CharacterOffsetEnd": "1",
"PartOfSpeech": "NN",
"CharacterOffsetBegin": "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"}'
您似乎有一个(
,我希望是{
。为什么要手动创建JSON?