【问题标题】:using jq to merge two json values based on key value使用jq根据key值合并两个json值
【发布时间】:2020-09-09 20:20:12
【问题描述】:

我有两个 json 文件,我想根据键的值合并它们。两个 json 文件中的键名不同,但值相同。我正在使用 jq 来尝试完成这项工作。我发现的大多数示例都是基于键名而不是值合并的。

sample1.json

 [
  {
    "unique_id": "pp1234",
    "unique_id_type": "netid",
    "rfid": "12245556890478",
 },
{
    "unique_id": "aqe123",
    "unique_id_type": "netid",
    "rfid": "12234556890478",
 }
] 

sample2.json

[
 {
 "mailing_state": "New York",
  "mobile_phone_number": "(982) 2541212",
  "netid": "pp1234",
  "netid_reachable": "Y",
 },
 {
 "mailing_state": "New York",
  "mobile_phone_number": "(982) 5551212",
  "netid": "aqe123",
  "netid_reachable": "Y",
 }
] 

我希望输出看起来像:

results.json

 [
      {
        "unique_id": "pp1234",
        "unique_id_type": "netid",
        "rfid": "12245556890478",
        "mailing_state": "New York",
        "mobile_phone_number": "(982) 2541212",
        "netid_reachable": "Y",
     },
     {
        "unique_id": "aqe123",
        "unique_id_type": "netid",
        "rfid": "12234556890478",
        "mailing_state": "New York",
        "mobile_phone_number": "(982) 5551212",
        "netid_reachable": "Y",
    }
]

只要记录基于 netid/unique_id 键合并,结果的顺序就无关紧要。如有必要,我愿意使用 jq 以外的东西。提前致谢。

【问题讨论】:

  • 请修复 JSON(例如运行 jq empty data.json 以查看故障点,或使用 jsonlint.com)。此外,据说预期的输出与输入文件不匹配。最后,由于 SO 不是免费的编程服务,请至少展示您解决问题的一种尝试。您可能会发现查看minimal reproducible example 的指南会有所帮助。

标签: json file merge jq key-value


【解决方案1】:

在更正示例输入文件后,以下调用应该可以解决问题:

jq --argfile uid sample1.json '
  ($uid | INDEX(.unique_id)) as $dict
  | map( $dict[.netid] + del(.netid) )
' sample2.json

如果您不想使用 --argfile 因为它已被弃用,您可以(例如)使用 --slurpfile 并将 jq 程序中的 $uid 更改为 $uid[0]。

【讨论】:

  • 感谢您的指点。我尝试使用提供的语法,它合并了第二条记录,但由于某种原因没有合并第一条记录。 (我还修复了原始示例中不正确的 unique_id。)
  • 你修复了输入文件吗?我已经验证了在修复它们之后,如图所示的调用会产生 results.json。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2020-12-28
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多