Combining JSON by common key-value pairs

后端 未结 1 1144
挽巷
挽巷 2021-01-16 05:15

I\'m currently working through an issue, and can\'t seem to figure this one out. Here\'s some data so you know what I\'m talking about below:

foo.json



        
相关标签:
1条回答
  • 2021-01-16 05:59

    With foobar.jq as follows:

    def dict(f):
      reduce .[] as $o ({}; .[$o | f | tostring] = $o ) ;
    
    ($bar | dict(.deviceId)) as $dict
    | .Schedule |= map(. + ($dict[.deviceId|tostring] ))
    

    the invocation:

    jq -f foobar.jq --argfile bar bar.json foo.json
    

    yields the output shown below.

    Notice that the referents in the dictionary contain the full object (including the key/value pair for "deviceId"), but it's not necessary to del(.deviceId) because of the way + is defined in jq.

    Output

    {
      "Schedule": [
        {
          "deviceId": 123,
          "reservationId": 123456,
          "username": "jdoe",
          "a": {
            "b": "10.0.0.1",
            "c": "hostname1"
          }
        },
        {
          "deviceId": 456,
          "reservationId": 589114,
          "username": "jsmith",
          "a": {
            "b": "10.0.0.2",
            "c": "hostname2"
          }
        }
      ],
      "serverTime": 1522863125.019958
    }
    
    0 讨论(0)
提交回复
热议问题