Reputation: 249
I want to convert the JSON into a job model to use it in API. below are the input and expected output. I also pasted the code which I used, but it's not working as expected. from tasks key we need to extract the values and make them as a separate list of models.
Input JSON
{
"id": "one",
"type": "db",
"tasks" : {
"process1" : ["j1", "j2"],
"process2" : ["j4"]
}
}
Expected Output :
{
"model": [
{
"data": [
{
"columnName": "tasks",
"columnValue": "j1"
},
{
"columnName": "process_name",
"columnValue": "process1"
}
]
},
{
"data": [
{
"columnName": "tasks",
"columnValue": "j2"
},
{
"columnName": "process_name",
"columnValue": "process1"
}
]
},
{
"data": [
{
"columnName": "tasks",
"columnValue": "j4"
},
{
"columnName": "process_name",
"columnValue": "process2"
}
]
}
]
}
I have tried with below code but it's not helping me out.
wanted_keys = ['tasks'] # The keys you want
task = dict((k, data[k]) for k in wanted_keys if k in data)
#print(type(task.items()))
ne = {}
for key, value in task.items():
ne = dict(value)
#print(ne)
jobModel = []
tableData = []
for key, value in ne.items():
#print(key)
for i in value:
#print(i)
tableData.append({'columnName': 'job_name', 'columnValue': i})
tableData.append({'columnName': 'jobplan_name', 'columnValue': key})
jobModel.append(tableData)
#print(tableData)
print(jobModel)
Upvotes: 1
Views: 42
Reputation: 17322
you can use:
from pprint import pprint
data = {
"id": "one",
"type": "db",
"tasks" : {
"process1" : ["j1", "j2"],
"process2" : ["j4"]
}
}
tasks_data = data['tasks']
new_data = []
for process, tasks in tasks_data.items():
for task in tasks:
new_data.append({'data': [
{'columnName': 'tasks', 'columnValue': task},
{'columnName': 'process_name', 'columnValue': process}]})
output = {'model': new_data}
pprint(output)
output:
{'model': [{'data': [{'columnName': 'tasks', 'columnValue': 'j1'},
{'columnName': 'process_name',
'columnValue': 'process1'}]},
{'data': [{'columnName': 'tasks', 'columnValue': 'j2'},
{'columnName': 'process_name',
'columnValue': 'process1'}]},
{'data': [{'columnName': 'tasks', 'columnValue': 'j4'},
{'columnName': 'process_name',
'columnValue': 'process2'}]}]}
Upvotes: 1