[英]How to print a specific item from within a JSON file into python
我想將 JSON 列表中的用戶打印到我選擇的 Python 中,但是我只能打印所有用戶。 如何打印特定用戶? 目前我有這個以丑陋的格式打印所有用戶
import json
with open('Admin_sample.json') as f:
admin_json = json.load(f)
print(admin_json['staff'])
JSON 文件如下所示
{
"staff": [
{
"id": "DA7153",
"name": [
"Fran\u00c3\u00a7ois",
"Ullman"
],
"department": {
"name": "Admin"
},
"server_admin": "true"
},
{
"id": "DA7356",
"name": [
"Bob",
"Johnson"
],
"department": {
"name": "Admin"
},
"server_admin": "false"
},
],
"assets": [
{
"asset_name": "ENGAGED SLOTH",
"asset_type": "File",
"owner": "DA8333",
"details": {
"security": {
"cia": [
"HIGH",
"INTERMEDIATE",
"LOW"
],
"data_categories": {
"Personal": "true",
"Personal Sensitive": "true",
"Customer Sensitive": "true"
}
},
"retention": 2
},
"file_type": "Document",
"server": {
"server_name": "ISOLATED UGUISU",
"ip": [
10,
234,
148,
52
]
}
},
{
"asset_name": "ISOLATED VIPER",
"asset_type": "File",
"owner": "DA8262",
"details": {
"security": {
"cia": [
"LOW",
"HIGH",
"LOW"
],
"data_categories": {
"Personal": "false",
"Personal Sensitive": "false",
"Customer Sensitive": "true"
}
},
"retention": 2
},
},
]
我就是搞不定。 任何幫助,將不勝感激。
謝謝。
您需要索引到staff
列表中,例如:
print(admin_json['staff'][0])
我建議閱讀一些Python 詞典。 字典值可以設置為任何對象:在這種情況下, staff
鍵的值設置為字典列表。 這是一個示例,它將遍歷所有員工並打印他們的姓名:
staff_list = admin_json['staff']
for person in staff_list:
name_parts = person['name']
full_name = ' '.join(name_parts) # combine name parts into a string
print(full_name)
嘗試這樣的事情:
import json
def findStaffWithId(allStaff, id):
for staff in allStaff:
if staff["id"] == id:
return staff
return {} # no staff found
with open('Admin_sample.json') as f:
admin_json = json.load(f)
print(findStaffWithId(admin_json['staff'], "DA7356"))
您可以列出所有用戶名
users = [user["name"] for user in admin_json['staff']]
此 JSON 文件中有兩個列表。 當您嘗試解析它時,您將獲得一個列表。 例如獲取第一個員工 ID:
print(admin_json['staff'][0]['id'])
這將打印:
DA7153
當您使用“json.loads”時,這只會將 JSON 文件轉換為 Python 字典。 更多信息: https : //docs.python.org/3/tutorial/datastructures.html#dictionaries
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.