簡體   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