【问题标题】:convert data struct to another data struct in Python在 Python 中将数据结构转换为另一个数据结构
【发布时间】:2023-03-27 03:53:01
【问题描述】:

我面临将 Python 中的一种数据结构转换为另一种数据结构(我认为是 JSON)的问题。 Python中有一些聪明的方法可以解决这个问题吗?也许是一些地图系统? 我可以采取什么方法来转换来自 CSV 文件的字典

{
   "id":1,
   "surname":"Einstein",
   "givennames":"Albert",
   "dateofbirth":"27/08/2007",
   "address":"11 Willow Road,BOSTON MANOR",
   "postcode":"AXT 5JA",
   "mobile":"078 1453 6934"
}

进入以下结构...

[
   {
      "metadata":{
         "type":"pole_model",
         "version":"0.1"
      },
      "party":[
         {
            "source_system":"A",
            "source_id":"1",
            "person":{
               "surname":"Einstein",
               "given_names":"Albert",
               "date_of_birth":"27/08/2007"
            }
         }
      ],
      "location":[
         {
            "source_system":"A",
            "source_id":"1",
            "address":{
               "line_1":"11 Willow Road,BOSTON MANOR",
               "postcode":"AXT 5JA"
            }
         },
         {
            "contact":{
               "source_system":"A",
               "source_id":"1",
               "phone":{
                  "mobile":"078 1453 6934"
               }
            }
         }
      ]
   }
]

【问题讨论】:

  • 我认为没有任何快速或内置的方法可以做到这一点。您可能需要自己编写代码
  • 好的,你知道我可以采取什么方法来实现这一目标吗?一些模板方法?也许映射?
  • 您必须先定义映射(即输入和输出之间的对应关系),然后想出一种编码方式。目前,您的输出包含比输入更多的数据(source_system 和元数据)。

标签: json python-3.x dictionary converters


【解决方案1】:

这是一种将源数据插入模板的简单方法。 metadatasource_system 值还可以传递给函数。

def convert(source):
    return {
      "metadata": {
         "type": "pole_model",
         "version": "0.1"
      },
      "party":[
         {
            "source_system": "A",
            "source_id": str(source["id"]),
            "person":{
               "surname": source["surname"],
               "given_names": source["givennames"],
               "date_of_birth": source["dateofbirth"]
            }
         }
      ],
      "location":[
         {
            "source_system": "A",
            "source_id": str(source["id"]),
            "address":{
               "line_1": source["address"],
               "postcode": source["postcode"]
            }
         },
         {
            "contact":{
               "source_system": "A",
               "source_id": str(source["id"]),
               "phone":{
                  "mobile": source["mobile"]
               }
            }
         }
      ]
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多