简体   繁体   English

Python:从 JSON 中提取变量

[英]Python: Extract Variables from JSON

I would like to extract a number of variables from a JSON-reponse and save it in a csv-file.我想从 JSON 响应中提取一些变量并将其保存在 csv 文件中。 The JSON-reponse looks as follows: 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

I would like to get the following variables: Name, Symbol, CoinName and ID我想获得以下变量:名称、符号、CoinName 和 ID

In order to extract all the values of the JSON-response, I use the following code:为了提取 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

However, I would like to extract only the specified variables.但是,我只想提取指定的变量。

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

I am not sure how I can modify this code to extract only the four specified variables?我不确定如何修改此代码以仅提取四个指定的变量? Can anyone help me with this.谁能帮我这个。 Thanks in advance,提前致谢,

If you want a list containing several specific values in your dict , you need to manually create a list:如果您希望在dict中包含多个特定值的列表,则需要手动创建一个列表:

mylist = [req['Name'], req['Symbol'], req['CoinName'], req['ID']]

Or, if you want a dict :或者,如果你想要一个dict

mydict = {'Name': req['Name'], 'Symbol': req['Symbol'],
          'CoinName': req['CoinName'], 'ID': req['ID']}

So to write this to a csv:因此,要将其写入 csv:

import csv

with open('coinList.csv', 'a') as filep:
    csvwriter = csv.writer(filep)
    csvwriter.writerow([req['Name'], req['Symbol'], req['CoinName'], req['ID']])

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

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