Issue
I have a JSON object with the following content:
{
"quiz": {
"sport": {
"id": "77",
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"13"
],
"answer": "13"
},
}
}
}
And I want to look for the KEY "id". And once is found, to start looking for the KEY "answer" and rename it to "answer_id".
Expected output:
{
"quiz": {
"sport": {
"id": "77",
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Huston Rocket"
],
"answer_id": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"13"
],
"answer": "12"
},
}
}
}
I've tried this so far what doesn't catch the field correctly:
awk ' { for ( i = 1; i <= NF; ++i ) {
if ( $i == "id" )
r = 1
if ( r && $i == "answer")
$i = "answer_id"
r = 0
}
}
1 ' example.json > example2.json
Solution
Here, one of solutions...
data = {
"quiz": {
"sport": {
"id": "77",
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"13"
],
"answer": "13"
},
}
}
}
for key in data.get('quiz'):
inner_data = data['quiz'][key]
if 'id' in inner_data and 'answer' in inner_data['q1']:
inner_data['q1']['answer_id'] = inner_data['q1'].pop('answer')
print(data)
Answered By - Andrei Gurko Answer Checked By - David Marino (WPSolving Volunteer)