jQuery-如果一个键/值存在于另一个JSON文件中,则将其添加到一个JSON文件

问题描述

只有一个JSON文件- landline.json

[
    {
        "City": "San Francisco","Person": "John Doe","Landline": false
    },{
        "City": "Los Angeles","Person": "Steve Smith","Landline": false
    }
]

还有另一个JSON文件- mobile.json

[
    {
        "City": "San Francisco","Mobile": false
    },"Person": "Jenny Miller","Mobile": false
    }
]

问题是如何使用 jq 的过滤器和条件语句创建"Landline": false的{​​{1}} "Mobile": false之后添加的新文件/数组?因此,结果数组应如下所示:

John Doe

因此算法应遵循-如果[ { "City": "San Francisco","Landline": false,"Landline": false } ] 中有mobile.json个条目,并且在同一块中有"Person": "John Doe"个条目,然后在{之后添加"Mobile": false个条目"Mobile": false"Landline": false的{​​1}}。

解决方法

对于这种类型的问题,“字典查找”很容易理解,并且给定jq的INDEX函数也很容易实现。考虑例如:

jq -n ' 
  def key: {City,Person};
  (input | INDEX(.[]; key) | map_values( {Mobile} ) ) as $mobile
  | input | map( . + $mobile[key|tostring] )
' mobile.json landline.json
,

这里是一个过滤器,可帮助您入门。使用 merge.jq 中的以下内容以及您指定的其他文件

def key: [.Person,.City] ;
[
      reduce .[][] as $e ({}; setpath($e|key; getpath($e|key) + $e)) 
    | .[][]
    | select(.Landline != null)
]

命令

jq -Ms -f merge.jq landline.json mobile.json 

产生

[
  {
    "City": "San Francisco","Person": "John Doe","Landline": false,"Mobile": false
  },{
    "City": "Los Angeles","Person": "Steve Smith","Landline": false
  }
]

要了解此处发生的情况,请观察此过滤器的作用

def key: [.Person,.City] ;
reduce .[][] as $e ({}; setpath($e|key; getpath($e|key) + $e)) 

从输入中构造一个临时嵌套的对象,其键为Person和City

{
  "John Doe": {
    "San Francisco": {
      "City": "San Francisco","Mobile": false
    }
  },"Steve Smith": {
    "Los Angeles": {
      "City": "Los Angeles","Landline": false
    }
  },"Jenny Miller": {
    "Los Angeles": {
      "City": "Los Angeles","Person": "Jenny Miller","Mobile": false
    }
  }
}

通过该对象的迭代和选择,可以将其转换回所需的形式,从而仅保留具有非空座机的对象。