Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq: selecting subset of keys from nested object

Tags:

json

nested

edit

jq

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!

like image 310
zopieux Avatar asked Oct 17 '25 18:10

zopieux


1 Answers

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

like image 177
jq170727 Avatar answered Oct 20 '25 08:10

jq170727