I have to manipulate nested json file in way that only one assignment stays.
How it looks now:
import json
a = '''
{
"tasks": [
{
"Assignments": [
{
"EmployeeId": "1000",
"TotalWork": 1,
"RemainingWork": 1
},
{
"EmployeeId": "3L2kVk00x",
"TotalWork": 1,
"RemainingWork": 1
},
{
"EmployeeId": "3L2kVk00y",
"TotalWork": 1,
"RemainingWork": 1
}
],
"TaskId": "487058",
"Project": 100
}
]
}
'''
data = json.loads(a)
How I want it to look.
{
"tasks": [
{
"Assignments": [
{
"EmployeeId": "1000",
"TotalWork": 1,
"RemainingWork": 1
}
],
"TaskId": "487058",
"Project": 100
}
]
}
I have written some code like this.
data = json.loads(a)
data = data['tasks'][0]['Assignments'].pop(0)
print(json.dumps(data, indent=2))
but the result is incorrect because it looks like this. There should be tasks and assignments before in it.
{
"EmployeeId": "1000",
"TotalWork": 1,
"RemainingWork": 1
}
Can you give me some tips?
2
Answers
Try this approach, re-assigning assignments
When working with large JSON data-set and happen to encounter some syntax errors, you might want to validate your JSON data using
JSONLint
which is one possible way.Instead of modifying the input data, it’s probably better to create a new structure based on the criteria as stated in the question.
The input data has a list as the value for ‘tasks’. Although there is only one element in that list you should allow for an arbitrary size.
Output: