passing arguments to jq filter

前端 未结 4 1903
孤城傲影
孤城傲影 2020-11-29 07:33

Here is my config.json:

{
    \"env\": \"dev\",
    \"dev\": {
        \"projects\" : {
            \"prj1\": {
                \"dependencies\": {},
                


        
相关标签:
4条回答
  • 2020-11-29 07:51

    As asked in a comment above there's a way to pass multiple argumets. Maybe there's a more elegant way, but it works.

    • If you are sure always all keys needed you can use this:
    jq --arg key1 $k1 --arg key2 $k2 --arg key3 $k3 --arg key4 $k4 '.[$key1] | .[$key2] | .[$key3] | .[$key4] '
    

    • If the key isn't always used you could do it like this:
    jq --arg key $k ' if key != "" then .[$key] else . end'
    

    • If key sometimes refers to an array:
    jq --arg key $k ' if type == "array" then .[$key |tonumber] else .[$key] end'
    

    of course you can combine these!

    0 讨论(0)
  • 2020-11-29 07:54

    The jq program .dev.projects."$v" in your example will literally try to find a key named "$v". Try the following instead:

    jq --arg v "$PRJNAME" '.dev.projects[$v]' config.json 
    
    0 讨论(0)
  • 2020-11-29 07:54

    you can do this:

    
        key="dev.projects.prj1"
        filter=".$key"
        cat config.json | jq $filter
    
    
    0 讨论(0)
  • 2020-11-29 08:00

    You can use --argjson too when you make your json.

    --arg a v       # set variable $a to value <v>;
    --argjson a v   # set variable $a to JSON value <v>;
    
    0 讨论(0)
提交回复
热议问题