返回JSON列表和PYTHON请求库

时间:2018-07-21 17:28:14

标签: python arrays json python-3.x

我正在使用python请求模块从3个不同的服务器获取JSON响应。 2个JSON响应如下所示:

JSON响应1:

{"MaleName1":"John","MaleAge1":"1.40531900","FemaleName1":"Anna","FemaleAge1":"14"}

JSON响应2:

{"male":[{"name":"John","age":"12"}],"female":[{"name":"Anna","age":"14"}]}

JSON响应3:

{"male":[["John","12",[]],["Alex","13",[]],["Glenn","12",[]],["Patrick","14",[]],["Gerard","14",[]]],"female":[["Anna","14",[]],["Lena","12",[]],["Martha","13",[]],["Penelope","13",[]],["Brenda","13",[]]]}

我的问题是解析第二个和第三个JSON响应的正确方法是什么,以便我可以打印以下所需的值:

1st Male Name: John
1st Male Age: 12
1st Female Name: Anna
1st Female Age: 14

对于第一个JSON响应,使用下面的 float() 参数获取所需的响应没有问题:

import json, requests

def 1stMaleName():
    1stMaleNameData = requests.get('url')
    return 1stMaleNameData.json()['MaleName1']
    1stMaleNameValue = float(1stMaleName())
    Print ("!st Male Name: ", 1stMaleNameValue)

2 个答案:

答案 0 :(得分:1)

第二个响应可以解析为:

In []:
ordinal = lambda n: {1:'st', 2:'nd', 3:'rd'}.get(n%10, 'th')

d = {"male":[{"name":"John","age":"12"}],"female":[{"name":"Anna","age":"14"}]}
for k, v in d.items():
    for i, s in enumerate(v, 1):
        print(f"{i}{ordinal(i)} {k.capitalize()} Name: {s['name']}")
        print(f"{i}{ordinal(i)} {k.capitalize()} Age: {s['age']}")

Out[]:
1st Male Name: John
1st Male Age: 12
1st Female Name: Anna
1st Female Age: 14

第三个响应:

In []:
d = {"male":[["John","12",[]],["Alex","13",[]],["Glenn","12",[]],["Patrick","14",[]],["Gerard","14",[]]],"female":[["Anna","14",[]],["Lena","12",[]],["Martha","13",[]],["Penelope","13",[]],["Brenda","13",[]]]}
for k, v in d.items():
    for i, s in enumerate(v, 1):
        print(f"{i}{ordinal(i)} {k.capitalize()} Name: {s[0]}")
        print(f"{i}{ordinal(i)} {k.capitalize()} Age: {s[1]}")

Out[]:
1st Male Name: John
1st Male Age: 12
2nd Male Name: Alex
2nd Male Age: 13
3rd Male Name: Glenn
3rd Male Age: 12
4th Male Name: Patrick
4th Male Age: 14
5th Male Name: Gerard
5th Male Age: 14
1st Female Name: Anna
1st Female Age: 14
2nd Female Name: Lena
2nd Female Age: 12
3rd Female Name: Martha
3rd Female Age: 13
4th Female Name: Penelope
4th Female Age: 13
5th Female Name: Brenda
5th Female Age: 13

注意:此f-strings在Py3.6 +中有效。对于.format(),例如:

f"{i}{ordinal(i)} {k.capitalize()} Name: {s['name']}"

等效于:

"{}{} {} Name: {}".format(i, ordinal(i), k.capitalize(), s['name'])

答案 1 :(得分:1)

对于第二个JSON查询: 1)遍历字典

2)遍历列表

3)遍历列表中的字典

这将使您更接近要搜索的内容。

请参阅example