我希望能够轻松解析我通过GET请求获得的JSON文件。我是新手,想要一些帮助。这是我从GET请求获得的JSON文件。
{
"Meta Data": {
"1. Information": "Intraday Prices and Volumes for Digital Currency",
"2. Digital Currency Code": "BTC",
"3. Digital Currency Name": "Bitcoin",
"4. Market Code": "CNY",
"5. Market Name": "Chinese Yuan",
"6. Interval": "5min",
"7. Last Refreshed": "2018-05-19 15:50:00",
"8. Time Zone": "UTC"
},
"Time Series (Digital Currency Intraday)": {
"2018-05-19 15:50:00": {
"1a. price (CNY)": "53014.32816681",
"1b. price (USD)": "8311.73569032",
"2. volume": "602.25300624",
"3. market cap (USD)": "5005767.80656960"
},
"2018-05-19 15:45:00": {
"1a. price (CNY)": "53013.58227123",
.......
我想返回我输入的任何加密硬币的最新美元价格。这是“时间序列(数字货币日内)”对象中的第一个对象。我如何在python中注明这一点?我知道怎么进入一个对象,因为我知道这个名字,但由于时间总是在变化,我怎么才进入第一个(即对象的索引)而不是名称“2018-05-19 15:50:00" 。这是我的代码与本节相关:
data = {'function' : 'DIGITAL_CURRENCY_INTRADAY', 'symbol' : 'BTC' , 'market' : 'CNY', 'apikey' : APIKey}
r = requests.get('https://www.alphavantage.co/query?',data)
data = r.json()
symbol = data['Meta Data']['2. Digital Currency Code'] #this works fine
print(symbol)
price = data['Time Series (Digital Currency Intraday)'] #how do I keep going in an say "the first index of Time Series.."?
print(price)
我知道这应该不会很难,但我已经浏览了整个互联网,并且无法对如何通过JSON文件做出明确答复。谢谢!
答案 0 :(得分:0)
这能解决您的问题吗?
答案 1 :(得分:0)
您可以使用data['Time Series (Digital Currency Intraday)']
dict.items()
的元素
dated_prices = data['Time Series (Digital Currency Intraday)']
for registered_date, prices in dated_prices.items():
# e.g. for first iteration, "registered_date" contains "2018-05-19 15:50:00"
usd_price = prices["1b. price (USD)"]
print(usd_price)
如果您只想获得第一次约会:
dated_prices = data['Time Series (Digital Currency Intraday)']
# Sort dates prices from the latest to the earliest
sorted_dated_prices = sorted(dated_prices.items(), key=lambda dp: dp[0], reverse=True)
# Get the latest dated price entry
latest_dated_price = sorted_dated_prices[0]
# Get the price (ignore the date)
latest_price = latest_dated_price[1]
# Get the dollar price
usd_price = latest_price["1b. price (USD)"]
print(usd_price)
答案 2 :(得分:0)
如果您熟悉Python的Pandas,您可以随时尝试使用pandas.read_json
。这会将您的数据放入一个pandas对象中,从而使传统的munging更容易。 recent_date = df['StartDate'].max()