繁体   English   中英

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

[英]Python - JSON Module how to query nested objects

我正在尝试使用Python作为引擎和JSON作为数据库文件来构建数据库支持的系统。 当前,有三个文件:

# 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"
    }
  }
}

但是,我找不到这样的方法来更改我的学生对象并仍然通过用户名查询:

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

有任何想法吗? 我是这种使用Python 3的新手。

在第二个示例中,用户属性在list内的字典

您将需要遍历列表,并使用所需的用户名获取字典。

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

请记住,由于用户名包含在它们自己的单独词典中,因此您现在可以具有重复的用户名,并且for循环方法将仅返回第一个匹配项。

我认为您可以使用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])

对于重复的用户名,您可以执行以下操作:

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