gpt4 book ai didi

python - 如果 json 键不存在则跳过

转载 作者:行者123 更新时间:2023-12-01 03:51:07 25 4
gpt4 key购买 nike

我正在运行以下命令:

for server in server_list:
for item in required_fields:
print item, eval(item)

某些 key 可能不存在,但更糟糕的是,它显示在父 key 上,而不是我正在扫描的 key 上。

所以我正在扫描 json 中的以下键:

server['server_management']['server_total_cost_of_ownership']['description']

它不存在,但实际上是 null 的父级:

server['server_management']['server_total_cost_of_ownership']

我该如何编写代码来解决这个问题?它没有给出关键错误。现在我得到以下回溯:

Traceback (most recent call last):
File "C:/projects/blah/scripts/test.py", line 29, in <module>
print item, eval(item)
File "<string>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'

完整代码:

import csv
import json
import os
import requests
import sys

required_fields = ["server['server_name']","server['server_info']['asset_type']['display_name']",
"server['asset_status']['display_name']", "server['record_owner']['group_name']",
"server['server_management']['server_total_cost_of_ownership']['description']",
"server['server_management']['primary_business_owner']['name']",
"server['environment']['display_name']", "server['is_virtual']",
"server['managed_by']['display_name']", "server['server_info']['billable_ibm']",
"server['server_info']['billing_sub_type']['display_name']",
"server['server_info']['serial_number']", "server['location']['display_name']",
"server['inception_date']", "server['server_info']['decommission_date']" ]

# Query API for all servers
def get_servers_info():
servers_info = requests.get('url')
return servers_info.json()

def get_server_info(sid):
server_info = requests.get('url')
return server_info.json()

server_list = get_servers_info()
for server in server_list:
for item in required_fields:
print item, eval(item)

最佳答案

事实上你应该避免 eval。 json 加载后,由于您知道键名称,因此可以使用列表深入树中。

server['server_management']['primary_business_owner']['name']" => ["server_management', 'primary_business_owner', 'name']

这里是针对必填字段列表进行 json 验证的片段。

data={
"d": {
"p":{
"r":[
"test"
]
}
},
"a": 3
}


def _get_attr(dict_, attrs):
try:
src = attrs[:]
root = attrs.pop(0)
node = dict_[root]
null = object()
for i, attr in enumerate(attrs[:]):
try:
node = node.get(attr, null)
except AttributeError:
node = null
if node is null:
# i+2 pop and last element
raise ValueError("%s not present (level %s)" % (attr, '->'.join(src[: i+2])))
return node
except KeyError:
raise ValueError("%s not present" % root)

# assume list of required field
reqs = [
["d", "p", "r"],
["d"],
["k"],
["d", "p", "r", "e"],
]

for req in reqs:
try:
_get_attr(data, req)
except ValueError as E:
print(E)
# prints
# k not present
# e not present (level d->p->r->e)

关于python - 如果 json 键不存在则跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38248746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com