在Python中用JSON对象解析文件

2024-09-27 00:11:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样结构的文件:

{ 
  "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']

这对我的处境很有效。下面的评论解释了可能有更好的方法。你知道吗


Tags: 文件对象keyapijsondata字典description
2条回答

另一种选择是在进行必要的更改后使用^{}模块中的^{}函数,以使其符合有效类型的格式:

from ast import literal_eval

inJson = '''{ 
  "key" : "A"
  "description" : "1"
  "uninterestingInformation" : "whatever"

}
{ 
  "key" : "B"
  "description" : "2"
  "uninterestingInformation" : "whatever"

}
{ 
  "key" : "C"
  "description" : "3"
  "uninterestingInformation" : "whatever"

}'''

inJson = "[" + inJson.replace("}", "},")[:-1] + "]"
inJson = inJson.replace("\"\n  ","\",")


newObject = literal_eval(inJson)
print(newObject)

输出:

[{'key': 'A', 'description': '1', 'uninterestingInformation': 'whatever'}, {'key': 'B', 'description': '2', 'uninterestingInformation': 'whatever'}, {'key': 'C', 'description': '3', 'uninterestingInformation': 'whatever'}]

您可以使用re.split将文件内容拆分为适当的JSON字符串进行解析:

import re
import json
j='''{ 
  "key" : "A",
  "description" : "1",
  "uninterestingInformation" : "whatever"

}
{ 
  "key" : "B",
  "description" : "2",
  "uninterestingInformation" : "whatever"

}
{ 
  "key" : "C",
  "description" : "3",
  "uninterestingInformation" : "whatever"

}'''
print(list(map(json.loads, re.split(r'(?<=})\n(?={)', j))))

这将输出:

[{'key': 'A', 'description': '1', 'uninterestingInformation': 'whatever'}, {'key': 'B', 'description': '2', 'uninterestingInformation': 'whatever'}, {'key': 'C', 'description': '3', 'uninterestingInformation': 'whatever'}]

相关问题 更多 >

    热门问题