I'm using python request module to get a JSON reponse from 3 different servers. The 2 JSON response look something like these:
JSON Response 1:
{"MaleName1":"John","MaleAge1":"1.40531900","FemaleName1":"Anna","FemaleAge1":"14"}
JSON Response 2:
{"male":[{"name":"John","age":"12"}],"female":[{"name":"Anna","age":"14"}]}
JSON Response 3:
{"male":[["John","12",[]],["Alex","13",[]],["Glenn","12",[]],["Patrick","14",[]],["Gerard","14",[]]],"female":[["Anna","14",[]],["Lena","12",[]],["Martha","13",[]],["Penelope","13",[]],["Brenda","13",[]]]}
My question is what is the correct approach to parse 2nd and 3rd JSON responses so I can print the following desired values:
1st Male Name: John
1st Male Age: 12
1st Female Name: Anna
1st Female Age: 14
For the 1st JSON response, I got no issue getting the desired response by using the argument below: 参数获取所需的响应没有问题:
import json, requests
def 1stMaleName():
1stMaleNameData = requests.get('url')
return 1stMaleNameData.json()['MaleName1']
1stMaleNameValue = float(1stMaleName())
Print ("!st Male Name: ", 1stMaleNameValue)
The second response can be parsed with:
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
And the 3rd response with:
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
Note: This f-strings
work in Py3.6+. For .format(), eg:
f"{i}{ordinal(i)} {k.capitalize()} Name: {s['name']}"
Is equivalent to:
"{}{} {} Name: {}".format(i, ordinal(i), k.capitalize(), s['name'])
For your 2nd JSON query: 1) Iterate through the dictionary
2) Iterate through the list
3) Iterate through the dictionary in the list
That will bring you close to what you're searching.
Please see an example .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.