jq:从嵌套对象中选择键的子集

时间:2017-10-22 17:13:10

标签: json nested edit jq

输入:

{"success": true, "results": {"a": …, "b": …, "c": …}}

期望的输出,因为我想保留b

{"success": true, "results": {"b": …}}

我尝试的事情:

$ jq 'del(select(.results.b | not))'
{"success": true, "results": {"a": …, "b": …, "c": …}}
# removes nothing from "results"

$ jq 'with_entries(select(.key == "success" or .key == "results.b"))'
{"success": true}
# nested comparison not understood; returns only "success"

谢谢!

2 个答案:

答案 0 :(得分:3)

这是一个解决方案:

{b'connection': b'keep-alive',
 b'accept': b'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
 b'host': b'localhost:4002',
 b'accept-language': b'en-us',
 b'user-agent': b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Safari/604.1.38',
 b'upgrade-insecure-requests': b'1',
 b'accept-encoding': b'gzip, deflate'
}

示例运行

.results |= {b}

Try it online at jqplay.org

答案 1 :(得分:0)

使用的另一种方式:

代码:

$ node<<EOF
var obj = $(</tmp/file.json);
delete obj.results.a;
delete obj.results.c;
console.log(JSON.stringify(obj));
EOF

输出:

{"success":true,"results":{"b":"bbb"}}
相关问题