问题描述:

I am currently trying to integrate a .json file into python, which includes currency instrument information from a data provider. My intentions are to be able to call list items, to be compared against each other (if candles[0] < candles[1]:, etc).

The .json file looks like this:

{

"instrument" : "EUR_USD",

"granularity" : "D",

"candles" : [

{

"time" : "2014-02-17T22:00:00Z",

"openMid" : 1.259445,

"highMid" : 1.259955,

"lowMid" : 1.251825,

"closeMid" : 1.257955,

"volume" : 61184,

"complete" : true

},

{

"time" : "2014-02-18T22:00:00Z",

"openMid" : 1.257975,

"highMid" : 1.259955,

"lowMid" : 1.251825,

"closeMid" : 1.252945,

"volume" : 67528,

"complete" : false

}

]

}

The python reader looks like this thus far:

#!/usr/bin/python

import json

with open('EURUSD.json', 'r') as eurusd_data:

data = json.load(eurusd_data)

data_string = json.dumps(data)

print data_string

What do I need to do in order to compare candle dictionary variables? For instance, candles[0] (with "volume" : 61184 variable), vs candles[1] (with "volume" : 67528 variable). I feel like there's something very simple I am missing here.

Also, if anyone is curious, I am receiving this data from Oanda's API (which is now free)

网友答案:

The json.load call gives you a dictionary with the exact structure of the JSON document you pasted (JSON documents are either JSON objects, which parse as dicts (as in your example), or JSON arrays, which parse as lists).

All you need to do is to compare data["candles"][0]["volume"] and data["candles"][1]["volume"] to get what you want.

网友答案:

sorted(data[candles], key=lambda candle:candle[volume]) gives you the candles sorted by volume in ascending order.

If you just want to order it and keep it in the data dictionary you just have to overwrite the old list of candles with the new one.

sorted_candles = sorted(data[candles], key=lambda candle:candle[volume])
data[candles] = sorted_candles
相关阅读:
Top