如何在JSON Python中比较两个值

如何在JSON Python中比较两个值,python,json,api,rest,Python,Json,Api,Rest,打印错误: import json import requests def names(threshold): data = requests.get("https://example.com/users/search?page={}") response = json.loads(data.content.decode('utf-8')) #print(response) for page in range(0, response[&quo

打印错误:

import json
import requests

def names(threshold):
    data = requests.get("https://example.com/users/search?page={}")
    response = json.loads(data.content.decode('utf-8'))
    #print(response)
    for page in range(0, response["total_pages"]):
        page_r = requests.get("https://example.com/users/search?page={}".format(page + 1))
        page_con = json.loads(page_response.content.decode('utf-8'))
        #print(page_con)
        for i in page_con["data"]:
            if i["bottles"] > threshold:
                return(i["name"])

print(names(10))
我所期望的是:

norman
在json中,我已经有15个名字了 P.S.2如果我将打印(I[“名称”])而不是返回(I[“名称”]),那么我将获得完整列表,但没有:

norman
oliver
Kyle
Zaaz
Chris
Jordan
Richard
Dora
Paul
Lena
我怎样才能修好它?请帮助

根据我所知(这是非常小的,因为您正在使用的url失败),您正在尝试索引到“Json”(您不是),并且您正在尝试将它的后续值与阈值变量的值进行比较

loads将返回python语言可以表示的数据结构,通常以列表、字典或字典列表的形式出现,以此类推。但是,您并没有在代码中检查这些内容,您只是试图从url获取数据结构,并在其中任意循环。因为您的代码没有运行,所以我使用jsonplaceholder api尝试重新创建您的问题

目前,您的代码中还存在一些其他问题,我想我最好解释并解决这些问题。尽我所能

python语言有一种称为“类型提示”的东西,它允许您建议变量的类型,或者函数返回的类型。与C++和其他静态类型语言不同,Python类型的提示仅仅是建议而不是命令。但它有助于代码的可读性,并在尝试遍历数据结构时对您有所帮助。遍历列表和字典是完全不同的事情。毕竟你不能处理数据,除非你知道数据的结构

您的比较在逻辑上是错误的,它不会过滤掉任何值, 另外,如果“i”的这个特定迭代没有一个名为“瓶子”的键,那么代码就会崩溃

norman
oliver
Kyle
Zaaz
Chris
Jordan
Richard
Dora
Paul
Lena
None
最好只写一行:

    if i["bottle"] > threshold:
#同时检查i[“name”]是否存在,它将不丢弃任何值
如果我[“瓶子”](列出或无):
"""
文档字符串很重要,是正确的IDE还是配置良好的Vim
或Emacs,将在您键入函数时显示这些文档字符串
名称
:如果API返回0,则引发:NotImplementedError
:param:我们想要的最大名称?
:return:仅名称列表,如果响应代码不是200,则无
:rtype:列表或无
"""
响应:请求。响应=\
请求。获取(“https://jsonplaceholder.typicode.com/users")
如果没有响应,状态\代码==200:
#API不工作,返回None,或者您也可以引发
#一个不同的错误,由你决定
一无所获
data:list=json.load(response.content.decode('utf-8'))
如果不存在(数据、列表):
#api给了我们一些东西,而不是列表
#我们的密码坏了
引发未实现的错误
#列一张清单,把所有的名字都放在里面
名称\容器:列表=[]
#数据是一个包含字典的列表
对于数据中的结构:
#现在,我们可以遍历这些键来查找匹配项

如果struct['id']Im不是python专家,但通常返回值只运行一次。因此,for循环将不可用。您可能必须声明一个数组,首先保存该数组中的值,然后在每次循环迭代时将其添加到该数组中。有意义吗?@lenz是对的,如果你想,你可以将名字保存在列表或字典中,然后返回列表或字典。你的标题和实际问题似乎没有什么关系,或者你可以
生成
值。
    # also check if i["names"] exists, it will discard None values
    if i["bottles"] <= threshold and i["name"]:
        print(i["name"])


    
import sys
import json
import requests


# Python is powerful, you can return different types of values
# from a single function, this arrow syntax demonstrates how to code
# that as a type hint
def names(threshold: int) -> (list or None):
    """
    Doc strings are important, a proper IDE, or a well configured Vim
    or Emacs, will show you these Doc strings when you type out a function
    name.

    :raises: NotImplementedError if API returns dictionaru
    :param: the maximum names we want?
    :return: list of only names, or None if response code is not 200
    :rtype: list or None
    """
    response: requests.Response = \
        requests.get("https://jsonplaceholder.typicode.com/users")

    if not response.status_code == 200:
        # API isnt working, return None, or you could also raise
        # a different error, up to you
        return None

    data: list = json.loads(response.content.decode('utf-8'))
    if not isinstance(data, list):
        # the api gave us back something other than a list
        # our code is borked
        raise NotImplementedError

    # make a list to hold all names in
    name_container: list = []
    # data is a list containing a dictionary basically
    for struct in data:
        # now we can iterate through the keys looking for a match
        if struct['id'] <= threshold and struct['name']:
            name_container.append(struct['name'])

    return name_container



if __name__ == '__main__':
    try:
        names: list = names(10)
    except NotImplementedError:
        sys.stderr.write("API changed on us, uh oh\n")
        # call some other function that handles it
        sys.exit(1)


    # the function can also return None, check for that before printing
    if names:
        for name in names:
            print(name)