简体   繁体   English

Python-JSON模块如何查询嵌套对象

[英]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. 我正在尝试使用Python作为引擎和JSON作为数据库文件来构建数据库支持的系统。 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. 我是这种使用Python 3的新手。

In your second example, you have the user attributes in a dictionary inside a list . 在第二个示例中,用户属性在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. 请记住,由于用户名包含在它们自己的单独词典中,因此您现在可以具有重复的用户名,并且for循环方法将仅返回第一个匹配项。

I think you can use lambda: 我认为您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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