我想为json.loads中不存在的密钥添加默认值
我有这样的键列表
["id", "name", "wkt", "created", "radius", "round"]
和许多行json文件,它们没有这样的键:
{"id":"1", "name":"a", "round":5}
{"id":"2", "wkt": "POINT(1.1)", "created":"2018-22-11T10:00:00"}
{"id":"3", "radius":3}
预期结果:
{"id":"1", "name": "a", "wkt":null, "created":null, "radius":null, "round":5}
我当前的解决方案
for line in lines:
line_dict = json.loads(line)
for key in keys:
if not key in line_dict:
line_dict[key] = None
yield line_dict
期望结果
我想找到一种更有效的方法来为json.loads中不存在的键设置默认值。到目前为止,使用object_hooks或object_pair_hook都没有成功。
答案 0 :(得分:1)
您可以初始化一个空值字典并进行相应的更新。
keys = ["id", "name", "wkt", "created", "radius", "round"]
default = dict.fromkeys(keys, None)
def read_json(filename):
with open(filename, 'r') as f:
for line in f:
d = default.copy()
d.update(json.loads(line))
yield d
答案 1 :(得分:0)
我可能会误解您的问题,但是您不能这样做吗?
def filler(d):
for i in ["id", "name", "wkt", "created", "radius", "round"]:
if i not in d:
d[i] = None
return d
json.loads('{"id":"1", "name":"a", "round":5}', object_hook=filler)
对我来说,这返回
{u'name': u'a', 'created': None, u'id': u'1', 'radius': None, 'wkt': None, u'round': 5}