我想从JSON响应中提取一些变量并将其保存在csv文件中。 JSON响应如下:
{
"Response":"Success",
"Message":"Coin list succesfully returned!",
"BaseImageUrl":"https://www.cryptocompare.com",
"BaseLinkUrl":"https://www.cryptocompare.com",
"DefaultWatchlist":{
"CoinIs":"1182,7605,5038,24854,3807,3808,202330,5324,5031,178978",
"Sponsored":"1182"
},
"Data":{
"USC":{
"Id":"100954",
"Url":"/coins/usc/overview",
"ImageUrl":"/media/1383363/usc.png",
"Name":"USC",
"Symbol":"USC",
"CoinName":"Ultimate Secure Cash",
"FullName":"Ultimate Secure Cash (USC)",
"Algorithm":"SHA256",
"ProofType":"PoS",
"FullyPremined":"0",
"TotalCoinSupply":"200084200",
"PreMinedValue":"N/A",
"TotalCoinsFreeFloat":"N/A",
"SortOrder":"1233",
"Sponsored":false
我想获得以下变量:名称,符号,CoinName和ID
为了提取JSON响应的所有值,我使用以下代码:
def getCoinList():
req = requests.get(‘https://www.cryptocompare.com/api/data/coinlist/’).json()
info = req[‘Data’]
coinList = pd.DataFrame(info)
coinList = coinList.transpose()
coinList.to_csv(‘coinList.csv’)
return coinList
但是,我想只提取指定的变量。
def getCoinList():
req = requests.get(‘https://www.cryptocompare.com/api/data/coinlist/’).json()['Data']
info = req['...'] /// How do I all four variables?
coinList = pd.DataFrame(info)
coinList = coinList.transpose()
coinList.to_csv(‘coinList.csv’)
return coinList
我不确定如何修改此代码以仅提取四个指定的变量?谁能帮我这个。提前谢谢,
答案 0 :(得分:1)
如果您想要一个包含dict
中几个特定值的列表,则需要手动创建一个列表:
mylist = [req['Name'], req['Symbol'], req['CoinName'], req['ID']]
或者,如果您想要dict
:
mydict = {'Name': req['Name'], 'Symbol': req['Symbol'],
'CoinName': req['CoinName'], 'ID': req['ID']}
所以把它写成csv:
import csv
with open('coinList.csv', 'a') as filep:
csvwriter = csv.writer(filep)
csvwriter.writerow([req['Name'], req['Symbol'], req['CoinName'], req['ID']])