Home > OS >  How do I open a json file and extract some extra data and saved them to varibles?
How do I open a json file and extract some extra data and saved them to varibles?

Time:06-02

I want to open this JSON file and extract everything that's in quotes in this JSON example and store them in their own individual variables to be used somewhere else. How do I do that?

{ "class": { "student1": { "studentID": "20345", "Campbell": { "Sims": {"grade": "5", "class_size": "30"} } }, "student2": { "studentID": "20022", "Williams": { "Johnson": {"grade": "3", "class_size": "25"} } } } }

CodePudding user response:

import json

file = open('data.json')

data = json.load(file)

individual_info = []

for i in data['class']:
    individual_data.append(i)
  
f.close()

in this code you are storing the data from the file temporarily in the variable i, then appending it to your list individual_data, which will persist after the loop concludes. What you do with that data, and how you access particular pieces, depends on the function of your program.

CodePudding user response:

import json

with open("test.json", "r") as f:
    data = json.load(f)

info_list = []
for k, v in data["class"].items():
    name = k
    id_, other_name, grade = "", "", ""
    for x, y in v.items():
        if "studentID" == x:
            id_ = y
        else:
            other_name = x
            grade = list(y.values())[0]["grade"]
    info_list.append((name, "studentID", id_, other_name, "grade", grade))
print(info_list)

OutPut

[('student1', 'studentID', '20345', 'Campbell', 'grade', '5'), ('student2', 'studentID', '20022', 'Williams', 'grade', '3')]
  • Related