Created
July 15, 2015 18:50
-
-
Save maurobaraldi/4496d3fa63704ed32118 to your computer and use it in GitHub Desktop.
Transform JSON string into Python objects (not dict)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from json import loads | |
from collections import namedtuple | |
def json_to_obj(data): | |
def hook(d): | |
return namedtuple('obj', d.keys())(*d.values()) | |
return json.loads(data, object_hook=hook) | |
>>> json_data = '{"lastUpdate": 1435608300000, "type": "stock", "timeOffSet": -10800000, "total": 5, "data": [{"date": 1428289200000, "high": 5.11, "price": 5.05, "open": 5.05, "low": 5.01}, {"date": 1427943600000, "high": 5.05, "price": 5, "open": 4.93, "low": 4.88}, {"date": 1427857200000, "high": 5.07, "price": 4.91, "open": 5.01, "low": 4.91}, {"date": 1427770800000, "high": 5.14, "price": 4.97, "open": 5.1, "low": 4.97}, {"date": 1427684400000, "high": 5.24, "price": 5.12, "open": 5.18, "low": 5.12}], "today": 1435697531409}' | |
>>> quotes = json_to_obj(json_data) | |
>>> quotes.lastUpdate | |
1435608300000L | |
>>> quotes.type | |
u'stock' | |
>>> quotes.data[0].open | |
5.05 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment