今天在观察python脚本的时候,看到了python解析jason数据这么一段。
经过相关查找,终于弄清楚了python是怎么解析jason结构,取得数据的。
我们通过以下命令:
target = urlopen(url, 'utf8') try: target = json.loads(target) except: print 'load json error!!'
取得了这么一段jason数据:
{ "title": "报表", "tables": { "example1": { "id": "first", "values": [ { "key": "one", "value": "1234" }, { "key": "two", "value": "12345" }, { "key": "three", "value": "123456" }, ] }, "example2": { "id": "second", "values": [ { "key": "four", "value": "321" }, { "key": "five", "value": "4321" }, }, } }
我们应该如何拿到里面的数据呢?比如说拿到key为“three”,value为“123456”的值,那么我们可以这样获取数据:
get_value = target['tables']['example1']['values'][2]['value']
首先,需要理解jason的结构:
而python会把对应的jason结构翻译过来,对应的关系如下:
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
所以我们使用 get_value = target['tables']['example1']['values'][2]['value'] 就可以得到“123456”这个值。
同理,使用 get_value = target['tables']['example2']['values'][0]['key']就可以得到“four”这个值了。
本文只是简单的分析,并没有深入研究,
待到对python的学习再深入一点再回头来看看,应该会有很大的改进!
:)