问题
How do I pass a variable argument to JQ program that will be used as a filter. Since by default --arg passes the argument as a a string wrapped with quotes the same cannot be used to apply a filter.
here is the JQ program that finds a particular path in the given json and adds a static key value to that path but doesn't work because of the quotes issue.
--argjson name '{ "pattern": "XYZ"}' 'def p: "." + (paths | select(.[-1] == "p-enum") | .[0:-1] | join(".")) ; .|p += $name' sample.json
here is the sample json
{
"type": "object",
"description": "Contains information.",
"properties": {
"type": {
"description": "Type.",
"type": "string",
"p-enum": [
{
"value": "IND",
"description": "Ind."
},
{
"value": "PROP",
"description": "Prop."
}
]
}
}
}
回答1:
Based on how I interpreted how you were using jq in your other question, it depends on how complicated your filter will be. Any argument that is to be interpreted by jq
is not the way you should approach it. This is the equivalent of using eval()
and is not only unsupported, but just not a good way to approach this.
If you're simply accessing a property of the input, you have a couple of ways using simple indexing or using getpath/1
for nested paths.
# indexing
# { "properties": ... }
$ jq --arg p 'properties' '.[$p]' input.json
# using getpath
# { "foo": { "bar": ... } }
$ jq --argjson path '["foo","bar"]' 'getpath($path)' input.json
来源:https://stackoverflow.com/questions/52174288/jq-pass-variable-argument-to-be-used-as-filter