python json数据格式
Python json模块
JSON(JavaScript Object Notation)是javascript对象表示法,它是一种基于文本,轻量级数据交换格式,
JSON有两种表示结构,一种是对象结构,一种是数组结构。
对象结构以{键:值}的形式表示,类似于字典的形式。
例如: { 1:{ "city_id":01, "city_name":"北京", "area":["城东区","城南区"] }, 2:{ "city_id":2, "city_name":"上海", "area":["浦东区","朝阳区"] } } 数组结构以[元素1,元素2,元素3]的形式表示。 例如: [ { "red":1, "blue":2, "green":3 }, { "apple":8, "banana":6 } ]
在Python中,提供json库来创建和解析json数据
json函数:
json.dumps() 将Python对象编码成json字符串
语法格式:
json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)
json.loads() 将已编码的json字符串解码为Python对象
语法格式:
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Python与json转化对照表:
Python json dict object list、tuple array str、unicode string int、long、float number True true False false None null
以下是Python创建json数据的实例
import json dist_1=[["a",1],["b",{"q":2,"w":6,"e":4,"r":3}]] json_1=json.dumps(dist_1) print json_1 运行结果: [["a", 1], ["b", {"q": 2, "r": 3, "e": 4, "w": 6}]] [Finished in 0.3s] [格式化数据] #-*-encoding:utf-8-*- import json dist_city={ 1:{ "city_id":01, "city_name":"北京", "area":["城东区","城南区"] }, 2:{ "city_id":2, "city_name":"上海", "area":["浦东区","朝阳区"] } } print dist_city #格式化输出json数据 json_city=json.dumps(dist_city,sort_keys=True,indent=4) print json_city 运行结果: {1: {'city_id': 1, 'city_name': '\xe5\x8c\x97\xe4\xba\xac', 'area': ['\xe5\x9f\x8e\xe4\xb8\x9c\xe5\x8c\xba', '\xe5\x9f\x8e\xe5\x8d\x97\xe5\x8c\xba']}, 2: {'city_id': 2, 'city_name': '\xe4\xb8\x8a\xe6\xb5\xb7', 'area': ['\xe6\xb5\xa6\xe4\xb8\x9c\xe5\x8c\xba', '\xe6\x9c\x9d\xe9\x98\xb3\xe5\x8c\xba']}} { #格式化后的json数据 "1": { "area": [ "\u57ce\u4e1c\u533a", "\u57ce\u5357\u533a" ], "city_id": 1, "city_name": "\u5317\u4eac" }, "2": { "area": [ "\u6d66\u4e1c\u533a", "\u671d\u9633\u533a" ], "city_id": 2, "city_name": "\u4e0a\u6d77" } } [Finished in 0.3s] [压缩] dist_1=[["a",1],["b",{"q":2,"w":6,"e":4,"r":3}]] json_1=json.dumps(dist_1) print "压缩前数据:%d" %(len(json_1)) #压缩 json_2=json.dumps(dist_1,separators=(",",":")) print "压缩后数据:%d" %(len(json_2)) 运行结果: 压缩前数据:51 压缩后数据:41 [Finished in 0.2s] loads函数 #-*-encoding:utf-8-*- import json dist_1=[["a",1],["b",{"q":2,"w":6,"e":4,"r":3}]] json_1=json.dumps(dist_1,indent=4,sort_keys=True,separators=(",",":")) print json_1 json_2=json.loads(json_1) #将json格式转换为Python关系的格式 print json_2 运行结果: [ [ "a", 1 ], [ "b", { "e":4, "q":2, "r":3, "w":6 } ] ] [[u'a', 1], [u'b', {u'q': 2, u'r': 3, u'e': 4, u'w': 6}]] [Finished in 0.2s]