[英]Transforming nested JSON to simple dictionary JSON structure
我正在调用一个 API,它以这种格式返回我的数据:
{
"records": [
{
"columns": [
{
"fieldNameOrPath": "Name",
"value": "Burlington Textiles Weaving Plant Generator"
},
{
"fieldNameOrPath": "AccountName",
"value": "Burlington Textiles Corp of America"
}
]
},
{
"columns": [
{
"fieldNameOrPath": "Name",
"value": "Dickenson Mobile Generators"
},
{
"fieldNameOrPath": "AccountName",
"value": "Dickenson plc"
}
]
}
]
}
为了在我的后续工作流程中正确使用这些数据,我需要一个结构,例如:
{
"records": [
{
"Name": "Burlington Textiles Weaving Plant Generator",
"AccountName": "Burlington Textiles Corp of America"
},
{
"Name": "Dickenson Mobile Generators",
"AccountName": "Dickenson plc"
}
]
}
所以fieldNameOrPath
值需要成为键, value
值需要成为值。
这个转换可以用 python function 完成吗?
这些条件适用:
columns
列表元素中会有多少个对象fieldNameOrPath
作为键的键和value
作为值的键传递给 function 以便指定它们)我们假设来自 API 的数据存储在变量data
中。 要将数据转换为您建议的格式,我们可以遍历所有记录,并通过遍历其列为每个记录创建一个字典,使用fieldNameOrPath
值作为键,使用value
作为字典值。
trans_data = {"records": []}
for record in data["records"]:
trans_record = {}
for column in record["columns"]:
trans_record[column["fieldNameOrPath"]] = column["value"]
trans_data["records"].append(trans_record)
我正在调用 API,它以以下格式返回数据:
{
"records": [
{
"columns": [
{
"fieldNameOrPath": "Name",
"value": "Burlington Textiles Weaving Plant Generator"
},
{
"fieldNameOrPath": "AccountName",
"value": "Burlington Textiles Corp of America"
}
]
},
{
"columns": [
{
"fieldNameOrPath": "Name",
"value": "Dickenson Mobile Generators"
},
{
"fieldNameOrPath": "AccountName",
"value": "Dickenson plc"
}
]
}
]
}
为了在我的以下工作流程中正确使用这些数据,我需要一个结构,例如:
{
"records": [
{
"Name": "Burlington Textiles Weaving Plant Generator",
"AccountName": "Burlington Textiles Corp of America"
},
{
"Name": "Dickenson Mobile Generators",
"AccountName": "Dickenson plc"
}
]
}
所以fieldNameOrPath
值需要成为键, value
值需要成为值。
这个转换可以用 python function 完成吗?
这些条件适用:
columns
列表元素中有多少对象fieldNameOrPath
作为键的键和value
作为值的键传递给 function 以便指定它们)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.