[英]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.