简体   繁体   English

如何从 web api 访问类似 json 的对象列表?

[英]How to access list of json-like objects from web api?

Just a side project I'm doing right now playing around with covid19 api.只是我现在正在做的一个附带项目,正在使用 covid19 api。 And I was hoping for something that would let me access the data with something like data2.countries .我希望有一些东西可以让我使用data2.countries东西访问数据。

import requests as r
import urllib
import json

url = 'https://api.covid19api.com/total/dayone/country/south-africa'
foo = urllib.request.urlopen(url)
data = json.loads(foo.read().decode())
data2 = json.parse(data)
print(data2)

The data looks like this - it's all in one list:数据如下所示 - 全部在一个列表中:

[{'Country': 'South Africa', 'CountryCode': '', 'Province': '', 'City': '', 'CityCode': '', 'Lat': '0', 'Lon': '0', 'Confirmed': 607045, 'Deaths': 12987, 'Recovered': 504127, 'Active': 89931, 'Date': '2020-08-22T00:00:00Z'},
 {'Country': 'South Africa', 'CountryCode': '', 'Province': '', 'City': '', 'CityCode': '', 'Lat': '0', 'Lon': '0', 'Confirmed': 609773, 'Deaths': 13059, 'Recovered': 506470, 'Active': 90244, 'Date': '2020-08-23T00:00:00Z'}]

So far I'm getting:到目前为止,我得到:

  File "~/20200813file/main.py", line 19, in <module>
    data2 = json.parse(data)

AttributeError: module 'json' has no attribute 'parse'

Why not try converting it into a pandas Dataframe.为什么不尝试将其转换为 Pandas Dataframe。

import urllib
import json
import pandas as pd

url = 'https://api.covid19api.com/total/dayone/country/south-africa'


foo = urllib.request.urlopen(url)

data = json.loads(foo.read().decode())

df = pd.DataFrame(data)

print(df.Country)

You should use json.dumps :你应该使用json.dumps

import requests as r
import urllib
import json

url = 'https://api.covid19api.com/total/dayone/country/south-africa'

foo = urllib.request.urlopen(url)
data = json.loads(foo.read().decode())
data2 = json.dumps(data)

print(data2)

json.dumps() function converts a Python object into a json string. json.dumps()函数将 Python 对象转换为 json 字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM