python圣斗士修炼(十六):json序列化

来源:互联网 发布:淘宝脐橙如何分类 编辑:程序博客网 时间:2024/06/04 17:44

JSON模块

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

python 原始类型向 json 类型的转化对照表:

Python JSON dict object list tuple array str unicode string int, long float number True true False false None null

在内存中序列化和反序列化:

a={'a':1,'b':2}x=json.dumps(a)//'{"a": 1, "b": 2}'json.loads(x)//{u'a': 1, u'b': 2}  #以uncode形式输出

序列化到文件,从文件中反序列化:

import jsonjsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'with open('json.txt','w')as f:    json.dump(jsonData,f)with open('json.txt','r')as fd://json.load()把文件内容转换成unicode数据类型返回    r = json.load(fd)    print r    print (type(r))

第三方模块demjson

Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。

Github 地址:https://github.com/dmeranda/demjson

官方地址:http://deron.meranda.us/python/demjson/
请根据以上地址自行安装。
这个模块使用起来很简单:
encode 将 Python 对象编码成 JSON 字符串
decode 将已编码的 JSON 字符串解码为 Python 对象

  • encode

Python encode() 函数用于将 Python 对象编码成 JSON 字符串。
语法

demjson.encode(self, obj, nest_level=0)
实例:
以下实例将数组编码为 JSON 格式数据:

import demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json以上代码执行结果为:[{"a":1,"b":2,"c":3,"d":4,"e":5}]
  • decode

Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。
语法

demjson.decode(self, txt)

以下实例展示了Python 如何解码 JSON 对象:

#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print  text以上代码执行结果为:{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
阅读全文
0 0