从网页下载JSON数据?

时间:2019-02-14 19:31:42

标签: python python-3.x python-requests stock

我正在尝试使用python从iex api下载数据,目前我可以获取数据,但现在我想对其进行格式化。

基本上,我得到了很多我不在乎的数据,我只想拥有“浮动”部分。

数据应如下所示:

代码,浮动,

AAPL,4700000000,(类似的东西)

我正在使用的代码:

import requests 

url = "https://api.iextrading.com/1.0/stock/aapl/stats" 

response = requests.get(url).json()

print (response)

如果有人可以解释我该怎么做,我会很高兴。

亲切的问候

现在我有了代码:

import requests 

url = "https://api.iextrading.com/1.0/stock/aapl/stats" 

response = requests.get(url).json()

data = (response['symbol'], response['float'])

import json filename='resp.json'

with open(filename, 'a+') as outfile:
    json.dump(data, outfile, indent=4)

import requests 

url = "https://api.iextrading.com/1.0/stock/tsla/stats" 

response = requests.get(url).json()

data = (response['symbol'], response['float'])

import json filename='resp.json'

with open(filename, 'a+') as outfile:
    json.dump(data, outfile, indent=4)

我希望数据显示为:

代码,浮动,

AAPL,4700000000,

TSLA,1700000000,

(不必在上面放置代码和浮动,我可以在excel功率查询中自己做到)。

2 个答案:

答案 0 :(得分:1)

您可以将其像字典一样对待。 response['float']会给您带来浮动。对于任何键都类似。

import requests
url = "https://api.iextrading.com/1.0/stock/aapl/stats"
response = requests.get(url).json()
print (response['float'])
print(response['symbol'])

输出

4705473314
AAPL

答案 1 :(得分:1)

您的代码正在执行应做的事情,如果您需要json的特定部分,请访问它。

import requests 

url = "https://api.iextrading.com/1.0/stock/aapl/stats" 

response = requests.get(url).json()

print(response['float'])
>4705473314
print(response['symbol'])
>'AAPL'

print(response['symbol'], response['float'])

要将response存储在json文件中,我们可以做类似的事情

import json
filename='resp.json'

with open(filename, 'w') as outfile:
    json.dump(response, outfile, indent=4)