簡體   English   中英

Jq - 如果另一個 JSON 文件中存在這樣的鍵/值,則將鍵/值添加到一個 JSON 文件

[英]Jq - add a key/value to one JSON file if such key/value exists in another JSON file

有一個 JSON 文件 -固定電話.json

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

還有另一個 JSON 文件 - mobile.json

[
    {
        "City": "San Francisco",
        "Person": "John Doe",
        "Mobile": false
    },
    {
        "City": "Los Angeles",
        "Person": "Jenny Miller",
        "Mobile": false
    }
]

問題是如何使用jq的過濾器和條件語句創建一個新的文件/數組,在"Landline": false "Mobile": false for John Doe之后添加? 因此生成的數組應如下所示:

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

所以算法應該如下 - 如果在mobile.json中有"Person": "John Doe"條目並且在同一塊中有"Mobile": false條目,然后在"Landline": false之后添加"Mobile": false條目"Landline": false for "Person": "John Doe" in 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)) 

構造一個臨時嵌套的 object,其鍵是來自輸入的 Person 和 City

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

從此 object 迭代和 select 用於轉換回所需的形式,僅保留具有非空陸線的對象。

對於這類問題,“字典查找”很容易理解,並且給定jq的INDEX function,也很容易實現。 考慮例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM