python - 从 JSON 对象生成特定字段

标签 python json

我有一个相当大的 JSON 对象,我正在尝试仅使用其中的某些元素生成特定的 JSON。

我当前的代码如下所示:

 data = get.req("/v2/users")
    data = json.loads(data)
    print (type(data)) # This returns <class 'list'>
    print (data) # Below for what this returns
    all_data = []
    for d in data:
        login_value = d['login']
        if login_value.startswith('fe'):
            continue
        s = get.req("/v2/users/" + str(login_value)) # Sending another request with each 
                                                     # login from the first request
        all_data.append(s)
        print (all_data) # Below for what this looks like this

print (data)json.loads之前是str作为信息,它返回的数据如下:

[
    {
        "id": 68663,
        "login": "test1",
        "url": "https://x.com/test"
    },
    {
        "id": 67344,
        "login": "test2",
        "url": "https://x.com/test"
    },
    {
        "id": 66095,
        "login": "hi",
        "url": "https://x.com/test"
    }
]

print (all_data) 对于第一次发送请求的每个用户都会返回与此类似的结果

[b'{"id":68663,"email":"x@gmail.com","login":"xg","phone":"hidden","fullname":"xg gx","image_url":"https://imgur.com/random.png","mod":false,"points":5,"activity":0,"groups":['skill': 'archery']}

这对每个用户都会重复。

我试图做的是从我收到的所有结果中过滤一些字段,所以我最终的 JSON 看起来像这样

[
   {
       "email": "x@gmail.com",
       "fullname": "xg gf",
       "points": 5,
       "image_url", "https://imgur.com/random.pmg"
   },
   {
        ... similar json for the next user and so on
   }
]

我觉得我迭代数据的方式可能效率低下,所以如果你能指导我找到更好的方法,那就太好了。

最佳答案

为了获取 login 值,您必须至少迭代一次数据,并且为了获取每个用户的详细信息,您必须进行一次调用,而这正是您所做的。

收到用户详细信息后,无需将整个对象附加到 all_data 列表,只需获取所需的字段并构造它的字典,然后将其附加到 all_data >.

所以你的代码的时间复杂度是 O(n),这是我最好的理解。

编辑:

对于每个用户,您都会收到如下所示的字节响应。

byte_response = [ b'{"id":68663,"email":"x@gmail.com","login":"xg","phone":"hidden","fullname":"xg gx","image_url":"https://imgur.com/random.png","mod":false,"points":5,"activity":0,"groups":[]}']

我不确定为什么你会在列表 [] 中得到响应,但如果是这样,那么就采用 byte_response[0] ,这样我们就有了如下所示的实际字节数据。

byte_response = b'{"id":68663,"email":"x@gmail.com","login":"xg","phone":"hidden","fullname":"xg gx","image_url":"https://imgur.com/random.png","mod":false,"points":5,"activity":0,"groups":[]}'

response_decoded = byte_response.decode("utf-8") #decode it

import json
json_object_in_dict_form = json.loads(response_decoded) #convert it into dictionary

然后...

json_object_in_dict_form['take the field u want']

关于python - 从 JSON 对象生成特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216649/

相关文章:

python - 如何在 Python 中测试 random.choice?

python - Ruby on Rails 是否与 Google Code API 配合得很好?

python - Scipy:Argrelmax 在 3d 数组中沿维度查找 Maxmima

javascript - ajax 根据从 URL 发送的 Json 对象执行操作

json - NXLog:Json 输入到 GELF UDP 输出

python - 重命名 groupby 的列名并使用 Pandas 计算结果

python - 求a到b范围内函数下的面积

javascript - 用 JSON 数组填充表时,AngularJS ng-repeat 创建三个空行

json - 我可以将 JSON 解码为接口(interface)的实现者吗?

javascript - 创建一个函数内带有 getJSON 的 jQuery 插件