python 当值为False时,从json解析布尔值并将其赋值给变量将不起作用

k4emjkb1  于 2023-02-21  发布在  Python
关注(0)|答案(1)|浏览(267)

使用Python,我得到了一个从API端点检索操作列表的函数,该函数接受一个filter参数作为变量,以便过滤给定 predicate 上的结果。
函数如下所示:

def list_operations(filter=None):
    # make a curl call to the product recognizer
    headers = {
        'Authorization': 'Bearer  {}'.format(creds.token),
        'Content-Type': 'application/json',
    }

    response = requests.get(
        'https://{}/v1alpha1/projects/{}/locations/us-central1/operations'.format(API_ENDPOINT, project),
        headers=headers
    )

    # dump the json response and display their names
    data = json.loads(response.text)

    #add a Metadata element to the operations if it does not exist
    for item in data['operations']:
        if not item.get('metadata'):
            item['metadata'] = {}
            item['metadata']['createTime'] = ''
        else:
            if not item['metadata'].get('createTime'):
                item['metadata']['createTime'] = ''        

    # Order operations by create time if the metadata exists and the createTime exists
    data['operations'] = sorted(data['operations'], key=lambda k: k['done'], reverse=True)

    if filter:
        # filter the operations by the filter value
        # Parse the filter value to get the operation name
        filter_path = filter.split('=')[0].split('.')
        filter_value = filter.split('=')[1]

        #check if the filter_value could be a Boolean
        if filter_value == 'True':
            filter_value = True 
        elif filter_value == 'False':
            filter_value = False

        # iterate backwards to avoid index out of range error using reversed
        for item in reversed(data['operations']):
            # for every element in filter_path, check if it exists
            item_value = item
            for filter_el in filter_path:
                if item_value.get(filter_el):
                    item_value = item_value.get(filter_el)

            
            # if the item value is not equal to the filter value, remove it from the list
            if item_value != filter_value:
                data['operations'].remove(item)

我的问题是当我用/调用函数时

list_operations(filter='done=False')

即使响应消息中的done键为False,对item_value的赋值也不起作用:

item_value = item_value.get(filter_el)

使用调试器时,item_value为{'name':“API程序接口路径/操作-1676883175156- 5 f51 dc 9 fc2 ad 1-b4 c56 f97-edd 1 e5 be”,“完成”:错误,“元数据”:{“创建时间”:“”}}而不是False
打电话时工作正常

list_operations(filter='done=True')

我看不出这里少了什么...
[编辑]问题是

if item_value.get(filter_el):

要测试密钥是否存在,应执行以下操作:

if filter_el in item_value:

愚蠢的错误...

tzdcorbm

tzdcorbm1#

json.loads()将JSON加载到Python字典中,因此"done": false已经在Python中转换为{"done": False}

import json

d = json.loads("""{"name": "api_path/operation-1676883175156-5f51dc9fc2ad1-b4c56f97-edd1e5be", 
"done": false, 
"metadata": {"createTime": ""}}""")
print(type(d['done']))
>>> <class 'bool'>

我没有你的全部答复,所以我不能帮助超过这一点。

相关问题