【问题标题】:Merge two files with different object types (patients and address)合并具有不同对象类型(患者和地址)的两个文件
【发布时间】:2022-01-21 22:49:33
【问题描述】:

我有两个文件:

  • patient.json:患者本身
  • address.json:患者地址

每个地址患者都包含其患者 ID。

patients.json:

{
  id: 1,
  name: "name1"
}
{
  id: 2,
  name: "name2"
}

patient_address.json:

{
  patient_id: 1,
  city: "city1-1",
  town: "town1-1"
}
{
  patient_id: 1,
  city: "city1-2",
  town: "town1-2"
}
{
  patient_id: 2,
  city: "city2-1",
  town: "town2-1"
}

我想要的结果是:

{
  id: 1,
  name: "name1",
  address: [
  {
    city: "city1-1",
    town: "town1-1"
  },
  {
    city: "city1-2",
    town: "town1-2"
  }]
},
{
  id: 2,
  name: "name2",
  address: [
  {
    city: "city2-1",
    town: "town2-1"
  }]
}

有什么想法吗?

【问题讨论】:

  • 你有没有尝试过自己解决这个问题?
  • 不,抱歉。我试图在查看一些文档时获得一些帮助,但我不太清楚如何开始......
  • 您是否在网站上查找过有关该主题的类似问题?
  • 是的,是的,但是我已经能够查找任何相关的帖子方法...

标签: json file join merge jq


【解决方案1】:

您的输入文件和预期的输出作为 JSON 无效,但暂时忽略这一点,您可以使用 jq 生成所需的转换,如下所示:

< patients.json jq --slurpfile address patient_address.json '
  (reduce $address[] as $a ({}; 
     .[ ($a.patient_id)|tostring].address += [$a | {city,town}] )) as $dict
  | . + $dict[.id|tostring]  
'

输出:

{
  "id": 1,
  "name": "name1",
  "address": [
    {
      "city": "city1-1",
      "town": "town1-1"
    },
    {
      "city": "city1-2",
      "town": "town1-2"
    }
  ]
}
{
  "id": 2,
  "name": "name2",
  "address": [
    {
      "city": "city2-1",
      "town": "town2-1"
    }
  ]
} 

有几种方法可以将您的输入转换为 JSON,例如使用 或类似工具。同样,如果您希望输出为 JSON 数组,您有多种选择,例如使用map

警告:上述解决方案假定.id|tostring 不会发生任何冲突。例如,如果 .id 始终是整数,就会出现这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 2019-06-09
    相关资源
    最近更新 更多