gpt4 book ai didi

json - 用于展平对象数组的 JMESPath 表达式,每个对象都有嵌套的对象数组

转载 作者:行者123 更新时间:2023-12-04 01:49:01 25 4
gpt4 key购买 nike

我有一个包含数据库数组的 JSON,每个数据库都有一个用户数组,例如

{"databases": [
{"db": "db_a", "users": [{"name": "alice"}, {"name": "alex"}]},
{"db": "db_b", "users": [{"name": "bob"}, {"name": "brienne"}]}
]}

我想生成一个平面数组和用户,即
[
{"db": "db_a", "name": "alice"},
{"db": "db_a", "name": "alex"},
{"db": "db_b", "name": "bob"},
{"db": "db_b", "name": "brienne"}
]

在 SQL 术语中,这将是笛卡尔连接或笛卡尔积,但我不确定树结构中的正确术语。到目前为止我最接近的是
databases[].users[]

产生
[{"name": "alice"}, {"name": "alex"}, {"name": "bob"}, {"name": "brienne"}]


databases[].{db: db, name: users[].name}

产生
[
{"db": "db_a", "name": ["alice", "alex"]},
{"db": "db_b", "name": ["bob", "brienne"]}
]

附录:我很高兴接受“你不能用 JMESPath 做到这一点,这就是为什么......”作为答案。安 HN Comment ``提示这个

can't reference parents when doing iteration. Why? All options for iteration, [* ] and map, all use the iterated item as the context for any expression. There's no opportunity to get any other values in

最佳答案

一个选项是 loop subelements

  tasks:
- set_fact:
my_db: "{{ my_db + [ item.0|combine(item.1) ] }}"
loop: "{{ lookup('subelements',databases,'users') }}"

关于json - 用于展平对象数组的 JMESPath 表达式,每个对象都有嵌套的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com