How can this be achieved?
Those are inputs:
ARRAY=["keyA", "keyC", "keyE"]
JSON={
"keyA": "valueA",
"keyB": "valueB",
"keyC": "valueC",
"keyD": "valueD",
"keyE": "valueE",
"keyF": "valueF"
}
So basing on what I have in ARRAY
(keys) how can I output corresponding keys and values from JSON
in order to have TARGET_JSON
like this:
TARGET_JSON={
"keyA": "valueA",
"keyC": "valueC",
"keyE": "valueE"
}
4
Answers
You can use the select function in jq to filter a JSON object based on the keys being in an array. for example
jq ‘select(keys_unmatched(["name", "city"]) | not)’ file.json
This is not JSON but javascript:
Here is one possible solution using
reduce
:Or with user-provided variables:
If you don’t care about the order of keys in the result (there is no inherent meaning to order of keys in JSON objects, because they are a bag of key-value pairs without order), then an alternative would be using
with_entries
, although it will be slower for large inputs:but this could be avoided by building a lookup/index object first: