简体   繁体   中英

jq: selecting subset of keys from nested object

Input:

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

Desired output, given I want to keep b :

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

Things I tried:

$ 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"

Thanks!

Here is one solution:

.results |= {b}

Sample Run

$ jq -M '.results |= {b}' <<< '{"success":true, "results":{"a": "…", "b": "…", "c": "…"}}'
{
  "success": true,
  "results": {
    "b": "…"
  }
}

Try it online at jqplay.org

Another way using and :

Code :

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

OUTPUT :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM