从Bittrex解析JSON

时间:2018-05-08 01:49:10

标签: python json urllib

我有这段代码:

import urllib2
import json
from matplotlib.finance import candlestick2_ohlc
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import datetime as datetime
import numpy as np
import csv

l = []
date = []
date_intermediaire = []

response = urllib2.urlopen('https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=BTC-ETH&tickInterval=thirtyMin&_=')
data = json.load(response)

其中data['result'][:]['T']包含时间,data['result'][:]['V']包含卷,data['result'][i]['O']包含开放,data['result'][i]['C']包含关闭,data['result'][:]['L']包含低,data['result'][:]['H'] {1}}包含高

实际上我想让这个定义更容易:

r['date'][i] = data['result'][i]['T']
r['open'][i] = data['result'][i]['O']
r['close'][i] = data['result'][i]['C']
r['max'][i] = data['result'][i]['H']
r['min'][i] = data['result'][i]['L']
r['volume'][i] = data['result'][i]['V']

但我不知道如何用Python做到这一点。

3 个答案:

答案 0 :(得分:1)

你可以使用熊猫:

import pandas as pd
...
df = pd.DataFrame.from_dict(data['result']) 
df.columns=['volume','close','max','min','open','date','last_column'] 
df.head()

输出:

      volume     close       max       min      open                 date  \
0  19.949007  0.056340  0.056560  0.056302  0.056340  2018-03-29T02:00:00   
1  28.811991  0.056302  0.056540  0.056301  0.056350  2018-03-29T02:30:00   
2  17.516028  0.056170  0.056488  0.056150  0.056302  2018-03-29T03:00:00   
3  33.393220  0.056030  0.056450  0.056020  0.056450  2018-03-29T03:30:00   
4  29.046574  0.055430  0.056140  0.055300  0.056030  2018-03-29T04:00:00   

   last_column  
0   354.123891  
1   511.145471  
2   311.468766  
3   594.549165  
4   521.328565  

答案 1 :(得分:0)

您想在此处“减少”您的数据。你可以在这里使用functools.reduce(),但是编写自己的函数可能会更容易。在每个结果上循环的东西,并将其附加到相关列。

def map_response(data):
    retval = {
      'date': [],
      'open': [],
      # ...
    }
    for result in data['result']:
       retval['date'].append(result['T'])
       retval['open'].append(result['O'])
       # ...

    return retval

您可以通过描述映射来更自动化这一点。

def map_response(data):
    mappings = {'T': 'date', 'O': 'open', '...': '...'}
    retval = {val: [] for val in mappings.values()}
    for result in data['result']:
        for key, value: result.items():
             retval[mappings[key]] = value

    return retval

但对我来说,看起来不太清楚,只是省去了重复。

答案 2 :(得分:0)

如果我理解正确,你不知道如何在解析的JSON中循环字典或列表

results = data['result']
r = []
for res in results:
    value = {}
    value['date']= res['T']
     # TODO: Get other values 
    r.append(value)