2011-06-09 140 views
2

我想解析解析JSON與Python

{"ticker":{"high":31.9099,"low":22.5,"vol":108468,"buy":29.61,"sell":30,"last":29.61}} 

,並結了:

last = 29.61 

,但我不知道從哪裏開始解析蟒蛇:(

+10

我真的不明白爲什麼這些問題總是被問到......在google中輸入「parse json python」直接導入Python'json'包。從那裏它應該是直截了當的。 – I82Much 2011-06-09 01:21:24

+2

@ I82Much,[擁抱非谷歌](http://meta.stackexchange.com/questions/5280/embrace-the-non-googlers) – 2011-06-09 01:34:12

+0

@Mike Pennington:當然,非谷歌搜索有很大的空間。他們可以使用Bing代替。或者他們可以啓動他們的Python庫手冊內容頁面並輸入Ctrl-Fjson – 2011-06-09 02:01:53

回答

13
>>> text = '''{"ticker":{"high":31.9099,"low":22.5,"vol":108468,"buy":29.61,"sell":30,"last":29.61}}''' 
>>> json.loads(text) 
{u'ticker': {u'sell': 30, u'buy': 29.609999999999999, u'last': 29.609999999999999, u'vol': 108468, u'high': 31.9099, u'low': 22.5}} 
>>> json.loads(text)[u'ticker'][u'last'] 
29.609999999999999 

或使用simplejson與舊版本的Python。

+0

爲什麼'u'ticker'而不是'ticker'? – 2013-05-20 10:52:48

+1

@KshitizSharma:因爲[''ticker''是字節,而不是文本。](http://farmdev.com/talks/unicode/) – 2013-05-20 10:54:10

2

我不確定,但我想我應該在這裏發佈這個以防其他人發現它有用。在Parsing JSON in Python這裏有一個很好的帖子 - 它很小,說明你如何在不同的場景中使用它。

祝你好運!