从JSON对象生成特定字段

问题描述 投票:0回答:1

我有一个相当大的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.loadsstr,它将返回如下数据:

[
    {
        "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":"[email protected]","login":"xg","phone":"hidden","fullname":"xg gx","image_url":"https://imgur.com/random.png","mod":false,"points":5,"activity":0,"groups":[]}

并且对每个用户重复一次。

我正在尝试从接收到的所有结果中按几个字段进行过滤,所以最终的JSON看起来像这样

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

[我感觉好像我遍历数据的方式可能效率低下,所以如果您可以指导我找到更好的方法,那将是很棒的。

python json
1个回答
0
投票

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

[在收到用户详细信息之后,没有将整个对象附加到all_data列表中,只需获取所需的字段并构造它的字典,然后将其附加到all_data

所以您的代码的时间复杂度为O(n),据我所知,这是最好的。

© www.soinside.com 2019 - 2024. All rights reserved.