Vu Le Anh
Vu Le Anh

Reputation: 756

JQ delete multiple properties

I have an object like this:

{
    "a" : 1,
    "b" : {
        "c" : {
            "c1" : "abc",
            "source" : "abcxyz"
        },
        "d" : {
            "d1" : "abcd",
            "source" : "abcxyz"
        },
        "e" : {
            "e1" : "abcde",
            "source" : "abcxyz"
        }
    }
}

My expectation is

{
    "a" : 1,
    "b" : {
        "c" : {
            "c1" : "abc"
        },
        "d" : {
            "d1" : "abcd"
        },
        "e" : {
            "e1" : "abcde"
        }
    }
}

I want to remove "source" properties. How can I do that without specifying keys "c", "d" or "e", because they are dynamic.

Upvotes: 21

Views: 16270

Answers (3)

jq170727
jq170727

Reputation: 14695

Here is another solution

del( .b[].source )

Upvotes: 20

user3899165
user3899165

Reputation:

Iterate through all the elements in .b, then set their value to the result of removing the .source element from them:

.b[] |= del(.source)

Upvotes: 25

ymonad
ymonad

Reputation: 12100

May be in next release of jq you can use builtin function walk/1. But current jq-1.5 don't have walk/1 so you have to copy it from buitin.jq https://github.com/stedolan/jq/blob/master/src/builtin.jq

save following code as hoo.jq

def walk(f):
  . as $in
  | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
    elif type == "array" then map( walk(f) ) | f
    else f
    end;

walk(if type == "object" then del(.source) else . end)

run

$ jq -f hoo.jq < YOUR_JSON.json

reference: recursive reduce arrays using jq

Upvotes: 4

Related Questions