Reputation: 170
I'm calling an API which returns me data in such a format:
{
"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"
}
]
}
]
}
in order to properly use this data for my following workflow I need a structure such as:
{
"records": [
{
"Name": "Burlington Textiles Weaving Plant Generator",
"AccountName": "Burlington Textiles Corp of America"
},
{
"Name": "Dickenson Mobile Generators",
"AccountName": "Dickenson plc"
}
]
}
So the fieldNameOrPath
value needs to become the key and the value
value needs to become the value.
Can this transformation be done with a python function?
Those conditions apply:
columns
list elementfieldNameOrPath
as the key for the key and value
as the key for the value to the function in order to specify them)Upvotes: 0
Views: 92
Reputation: 91
We'll suppose the data from the API is stored in a variable data
. To get the data transformed into the format you propose, we can iterate through all the records, and for each record create a dictionary by iterating through its columns, using the fieldNameOrPath
values as the keys, and the value
values as the dictionary values.
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)
Upvotes: 2