简体   繁体   中英

Python - JSON Module how to query nested objects

I am trying to build a database-backed system using Python as an engine and JSON as the DB file. Currently, there are three files:

# functions.py
import json
from pprint import pprint

with open('db.json') as data_file:
    data = json.load(data_file)


def getStudentByUsername(username, record):
    detail = json.load(open('db.json'))["students"][username][record]
    pprint(detail)

# main.py
import functions


functions.getStudentByUsername('youngh', 'age')

{ // db.json
  "students": {
    "youngh": {
      "name": "Hayden Young",
      "age": 13,
      "email": "user@school.county.sch.uk"
    }
  }
}

But, I can't find a way to change my students object like this and still query by username:

{ //db.json "students": [
  {
    "username": "youngh",
    "name": "Hayden Young"
  }]
}

Any ideas? I'm new to this type of use of Python 3.

In your second example, you have the user attributes in a dictionary inside a list .

You will need to iterate over your list and get the dictionary with the username you seek.

with open('db.json') as dbfile:
    for student in json.load(dbfile)["students"]:
        if student["username"] == username:
            return(student)

Keep in mind that because the usernames are contained in their own separate dictionaries, you can now have duplicate usernames, and the for loop method will only return the first match.

I think you can use lambda:

#let this var be your file output after parsing to json
users = { 
    "students": 
    [
       {
            "username": "youngh",
            "name": "Hayden Young"
        }
    ]
}

def getStudentByUsername(username, record):    
    detail= filter(lambda user: username == user['username'], users["students"])
    print (next(detail)[record])

For duplicate usernames, you can do something like this:

def getStudentByUsername(username, record):    
    detail= filter(lambda user: username.lower() == user['username'].lower(), users["students"])    
    while True:
        try:
            print (next(detail)[record])
        except StopIteration:
            return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM