jq retain missing array objects from capturing group and update array

前端 未结 3 2055
后悔当初
后悔当初 2021-01-29 03:47

Input

[{
        \"tags\": [{
                \"value\": \"domain:sourcing\"
            },
            {
                  


        
相关标签:
3条回答
  • 2021-01-29 04:21

    If the "value" part of the "tag:value" strings might contain a colon (":"), then using split becomes unnecessarily tricky (and maybe even inefficient), so it might be easier to use capture, perhaps along the lines suggested by @RomanPerekhrest:

    {domain:"-", apiname:"-"} as $default
    | map([.tags[].value
           | capture("(?<k>[^:]*):(?<v>.*)")
           | {(.k): .v} ]
          | add
          | $default + .)
    
    0 讨论(0)
  • 2021-01-29 04:27

    jq solution:

    jq '{domain: "-", apiname: "-"} as $o 
        | map([.tags[] | .value | split(":") | {(.[0]) : .[1]}] | add | $o + .)' input.json
    
    • {domain: "-", apiname: "-"} as $o - used as a template object

    The output:

    [
      {
        "domain": "sourcing",
        "apiname": "src1"
      },
      {
        "domain": "-",
        "apiname": "fin1"
      },
      {
        "domain": "fin1",
        "apiname": "-"
      }
    ]
    
    0 讨论(0)
  • 2021-01-29 04:35

    Here's another approach. This assumes your tags array will only contain the names you expect.

    map(
        reduce (.tags[].value | split(":")) as [$k,$v] (
            {domain:"-",apiname:"-"};
            .[$k] = $v
        )
    )
    

    For a more general solution that doesn't assume fixed names and just flattens the tags, I'd do this:

    map(
        reduce (.tags[].value | split(":")) as [$k,$v] (
            del(.tags);
            .[$k] = $v
        )
    )
    

    Then as you access the fields, just use the alternative operator to set the default value.

    (.domain // "-") as $domain
    
    0 讨论(0)
提交回复
热议问题