我积极解决 发表于 2017-4-25 06:19:12

python解析jason数据

  今天在观察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']['value']
  首先,需要理解jason的结构:

 写道

JSON建构于两种结构:
      “名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
      值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

 写道

JSON具有以下这些形式:

对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。



 

数组是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。



 

值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。



 
  而python会把对应的jason结构翻译过来,对应的关系如下:

  JSON
 Python

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']['value'] 就可以得到“123456”这个值。
  同理,使用 get_value = target['tables']['example2']['values']['key']就可以得到“four”这个值了。
  本文只是简单的分析,并没有深入研究,
  待到对python的学习再深入一点再回头来看看,应该会有很大的改进!
  :)
  参考:http://www.json.org/json-zh.html
  http://docs.python.org/library/json.html
页: [1]
查看完整版本: python解析jason数据