我正面临着将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"
}
}
}
]
}
]
这是一个将源数据插入模板的简单方法。metadata
和source_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"]
}
}
}
]
}