Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
processing nested json data
#1
Hi,
i need help to flatten the below json data by removing from "Answers" where "answer1" is null('') :

"body": [
{
"responseId": 1,
"answers": [
{
"answer1": "",
"questionId": "r67be312f34474793b802cdb35a719e5f"
},
{
"answer1": {
"id": 1,
"order": 3,
"displayText": "Fair"

},
"questionId": "r932bd3d18d4e4af2ba8174333c86a5dc"
},
{
"answer1": "7 to 9 years",
"questionId": "r44d182a9e27d4b0c902862362c2da4db"
},

{
"answer1": {
"id": 6,
"order": 1751924912753,
"displayText": "N/A"

},
"questionId": "rc4e8608191e24d76bf1c568a384f23bf"
}
]
}
]


any help is appreciated - thanks.
Reply
#2
If you print your json using pprint, you can see the structure more clearly, then you know how to get what you want.

The loaded json file just consists of dictionaries and lists.

import json
from pathlib import Path
from pprint import pprint

"""
When you load the .json file with data = json.load(f) you have a dictionary of dictionaries and maybe lists
Then you can do all the things Python dictionaries can do.
"""

# your json saved as text file
mypath = '/home/peterr/temp/myjson1.json'

# check if the json you want exists
chk_file = Path(mypath) 
if chk_file.is_file():
    print(mypath, 'exists, so open it ... \n\n')
    with open(mypath) as f:
        data = json.load(f)
else:
    print("File does not exist, so make data an empty dictionary!\n\n")
    data = {}  

# see the structure more clearly using pprint
pprint(data)
# collect the data in a list if d['answer1'] != ''
wanted = []
for d in data['body'][0]['answers']:
             print(d)
             if d['answer1'] != '':
                 wanted.append(d)

pprint(wanted)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Save JSON data to sqlite database on Django Quin 0 4,521 Mar-26-2022, 06:22 PM
Last Post: Quin
  Extract json-ld schema markup data and store in MongoDB Nuwan16 0 3,824 Apr-05-2020, 04:06 PM
Last Post: Nuwan16
  Paginate json data in flask or jinja2 soli1994 1 10,226 Jun-28-2018, 06:00 PM
Last Post: gontajones

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020