Use jq to turn x=y pairs into key/value pairs

后端 未结 2 804
轻奢々
轻奢々 2020-12-11 09:18

I\'m trying to parse environment variables from the JSON output of docker inspect. Annoyingly, those environment variables aren\'t returned as useful key-value

相关标签:
2条回答
  • 2020-12-11 10:02

    To convert an array of two strings (e.g. ["k", "v"]) to an object, you can write:

    { (.[0]) : .[1] }
    

    So you'll want to write something like:

     map(.Config.Env |= (map( split("=") | { (.[0]) : .[1] } ) | add))
    

    a2o

    Abstracting out the array-to-object functionality makes the solution a bit more digestible:

    def a2o: map( split("=") | { (.[0]) : .[1] } ) | add;
    
    map(.Config.Env |= a2o)
    

    Using match or capture instead of split

    Since it is possible for an "=" character to appear in the "value" part of each var=value string, using split naively might not be such a great idea. Here is a more robust alternative, assuming your jq supports regular expressions:

    match("([^=]*)=(.*)") | .captures | {(.[0].string) : .[1].string}
    

    Or, slightly more succinctly and perhaps elegantly:

    [capture( "(?<key>[^:]*):(?<value>.*)" )] | from_entries
    

    index/1

    If your jq does not have regex support, you could use index/1, along these lines:

    index("=") as $ix | {(.[:$ix]) : .[$ix+1:]}
    
    0 讨论(0)
  • 2020-12-11 10:20

    Given collection of items to convert to a single object, I generally would opt to using reduce for this purpose. Turn those items to their constituent keys and values, then assign to the result object.

    reduce (.[] | split("=")) as [$key, $value] ({}; .[$key] = $value)
    

    Though using from_entries is also useful here as well, instead you'd create an array of the key/value objects that it expects.

    map(split("=") as [$key, $value] | {$key, $value}) | from_entries
    

    Then put it all together with the update of the Env property using whichever method you choose.

    .[].Config.Env |= reduce (.[] | split("=")) as [$key, $value] ({}; .[$key] = $value)
    #or
    .[].Config.Env |= (map(split("=") as [$key, $value] | {$key, $value}) | from_entries)
    

    https://jqplay.org/s/qfItW5U-Tf

    0 讨论(0)
提交回复
热议问题