【发布时间】:2021-08-02 15:15:55
【问题描述】:
使用 jsonpath_ng 解析 JSON 对象时,有没有办法强制丢失的字段返回 None? 澄清一下,我不是在寻找如何使用任何其他方法来做到这一点,只是使用 jsonpath_ng(或其他 Python JSONPath 解析器)。
我希望最终列表的长度相同。这是一个非常简单的例子,我的实际用例需要使用某种程序解析:
from jsonpath_ng import parse
data = {
'source': 'api',
'data': {
'records': [
{
'id': '1',
'value': 10
},
{
'id': '2'
},
{
'id': '3',
'value': 30
},
]
}
}
# Default behavior
ids = parse('$.data.records[*].id').find(data)
values = parse('$.data.records[*].value').find(data)
print([
(i.value, j.value)
for i, j in zip(ids, values)
])
# using the ``jsonpath.auto_id_field`` setting seems to target similar issue,
# but not exactly what I need:
jsonpath.auto_id_field = 'values' # this seems to
ids = parse('$.data.records[*].id').find(data)
values = parse('$.data.records[*].value').find(data)
print('Using jsonpath.auto_id_field = "value"')
print([
(i.value, j.value)
for i, j in zip(ids, values)
])
输出:
[('1', 10), ('2', 30)]
Using jsonpath.auto_id_field = 'value'
[('1', 'data.records.10'), ('2', 'data.records.[1]'), ('3', 'data.records.30')]
这显然是不正确的。期望的输出:
[('1', 10), ('2', None), ('3', 30)]
【问题讨论】: