jq: pass variable argument to be used as filter [duplicate]

二次信任 提交于 2021-02-05 12:26:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!