我有一个这样结构的文件:
{
"key" : "A",
"description" : "1",
"uninterestingInformation" : "whatever"
}
{
"key" : "B",
"description" : "2",
"uninterestingInformation" : "whatever"
}
{
"key" : "C",
"description" : "3",
"uninterestingInformation" : "whatever"
}
我想用Python构建一个字典,其中包含键作为键,描述作为值。我有更多的领域,但只有其中2个是我感兴趣的。你知道吗
这个文件并不完全是一个.json文件,而是一个包含许多类似json对象的文件。你知道吗
你知道吗json.loads文件显然,它不起作用。你知道吗
关于如何读取数据有什么建议吗?你知道吗
我已经读过this post,但是我的json对象不在一行上。。。你知道吗
编辑:
如果在我的解释中不清楚的话,这个例子是相当准确的,我有很多类似的JSON对象,一个接一个,用新行(\n)分隔,没有逗号。所以,总的来说,这个文件不是一个有效的JSON文件,而每个对象都是一个有效的JSON对象。你知道吗
我最终采用的解决方案是:
api_key_file = open('mongo-config.json').read()
api_key_file = '[' + api_key_file + ']'
api_key_file= api_key_file.replace("}\n{", "},\n{")
api_key_data = json.loads(api_key_file)
api_key_description = {}
for data in api_key_data:
api_key_description[data['apiKey']] = data['description']
这对我的处境很有效。下面的评论解释了可能有更好的方法。你知道吗
另一种选择是在进行必要的更改后使用^{} 模块中的^{} 函数,以使其符合有效类型的格式:
输出:
您可以使用
re.split
将文件内容拆分为适当的JSON字符串进行解析:这将输出:
相关问题 更多 >
编程相关推荐