PyCon 2011 - Hidden Treasures of the Python Standard Library - json序列化操作
2011-03-30 00:19
681 查看
本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 Unported许可协议进行许可。允许非商业转载,但应注明作者及出处。
作者:liuyuan_jq
2011-03-30
json简介
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#,
Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
json资源
http://www.json.org/json-zh.htmlhttp://woodpecker.org.cn/diveintopython3/serializing.html
simplejson
如果你使用的是python2.6以下的版本,需要手动安装simplejson支持jsoneasy_install simplejson
自定义序列化对象
#!/usr/bin/env python # encoding: utf-8 # json_myobj.py """ Define a class to be encoded. """ class MyObj(object): def __init__(self, s): self.s = s def __repr__(self): return '<MyObj(%s)>' % self.s
dumps操作
#!/usr/bin/env python # encoding: utf-8 # json_dump_default.py """Serialize a custom object to JSON. """ import hmac import json_myobj try: import json except: import simplejson as json """ # python json_dump_default.py { "s" : "instance value goes here", "__module__" : "json_myobj", "__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77", "__class__" : "MyObj" } """ def convert_to_builtin_type(obj): """object->dictionary""" print 'convert_to_builtin_type(%r)' % obj # convert_to_builtin_type(<MyObj(instance value goes here)>) class_name = obj.__class__.__name__ module_name = obj.__module__ digest_maker = hmac.new('PyCon2011', # 公钥 module_name + class_name) # 发送的信息 signature = digest_maker.hexdigest() # 生成摘要 d = { '__class__':class_name, '__module__':module_name, '__signature__':signature, } d.update(obj.__dict__) return d obj = json_myobj.MyObj('instance value goes here') print json.dumps(obj, default=convert_to_builtin_type)
loads操作
#!/usr/bin/env python # encoding: utf-8 """Load a custom object from JSON serlized version. """ import hmac try: import json except: import simplejson as json def dict_to_object(d): if '__class__' not in d: return d class_name = d.pop('__class__') module_name = d.pop('__module__') signature = d.pop('__signature__') digest_maker = hmac.new('PyCon2011', module_name + class_name) expected_signature = digest_maker.hexdigest() if signature != expected_signature: raise ValueError('Invalid signature') print 'Loading "%s" from "%s"' % / (class_name, module_name) module = __import__(module_name) class_ = getattr(module, class_name) args = dict( (key.encode('ascii'), value) for key, value in d.items()) print 'Instantiating with', args inst = class_(**args) return inst for encoded_object in [ ''' [{"s": "instance value goes here", "__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77", "__module__": "json_myobj", "__class__": "MyObj"}] ''', # careful! ''' [{"path": "/etc/passwd", "__signature__": "426f662f9fe3b3533d9ce7f9dcf8af77", "__module__": "os", "__class__": "unlink"}] ''', ]: try: myobj_instance = json.loads( encoded_object, object_hook=dict_to_object, ) print myobj_instance except Exception, err: print 'ERROR:', err print
相关文章推荐
- PyCon 2011 - Hidden Treasures of the Python Standard Library - Source code
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 词法分析器分析命令行参数
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 将sqlite3的查询输出转化为python列表格式
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 邮件地址正则表达式匹配
- PyCon 2011 - Hidden Treasures of the Python Standard Library
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 全局异常捕获
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 解析电子邮件地址
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 获得夏时令标识符
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义sqlite3数据表字段数据类型
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 为Python命令行添加了按键自动补全内容和命令历史功能
- PyCon 2011 - Hidden Treasures of the Python Standard Library - logging日志处理
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 模拟hmac摘要算法的实现
- PyCon 2011 - Hidden Treasures of the Python Standard Library - 自定义交互模式表达式计数器
- Python语言中对于json数据的编解码——Usage of json a Python standard library
- [python3教程]第十章.标准库简介(Brief Tour of The Standard Library)
- The Python Standard Library » 5. Built-in Types 2. Built-in Functions
- C++中使用array报错 requires compiler and library surpport for the ISO c++ 2011 standard
- error: #error This file requires compiler and library support for the ISO C++ 2011 standard.
- 【Python基础】之对字典进行排序操作(sort by the values of dict)
- Question 6: Which of the following are container adapters in the STL (Standard Template Library) in C++?