python 中json的使用方法

Json简介:Json,全名 JavaScript Object Notation,是一种轻量级的数据交换格式。Json最广泛的应用是作为AJAX中web服务器和客户端的通讯的数据格式。现在也常用于http请求中,所以对json的各种学习,是自然而然的事情。Python的官网网址:https://docs.python.org/2/library/json.html?highlight=json#module-json下面是官网的内容翻译。

基本的python对象编码

import json
json.dumps(['foo',{'bar':('baz',None,1.0,2)}])
print json.dumps("\"foo\bar")
print json.dumps(u'\u1234')
print json.dumps('\\')
print json.dumps({"c":0,"b":0,"a":0},sort_keys=True)
fom StringIO import StringIO
io = StringIO
json.dump(['streaming API'],io)

完整的编码

json.dumps([1,2,3,{'4':5,'6':7}],separators=(',',':'))

完美打印

print json.dumps({'4':5,'6':7},sort_keys=True,---    indent = 4,separators=(',',':'))

解码 json :

 import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
u'"foo\x08ar'
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
[u'streaming API']

特定的JSON 对象 解码 :

>>> import json
>>> def as_complex(dct):
...     if '__complex__' in dct:
...         return complex(dct['real'], dct['imag'])
...     return dct
...
>>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
...     object_hook=as_complex)
(1+2j)
>>> import decimal
>>> json.loads('1.1', parse_float=decimal.Decimal)
Decimal('1.1'

json 编码延伸

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return [obj.real, obj.imag]
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[', '2.0', ', ', '1.0', ']']

从shell 中使用 json工具 去验证和完整打印

$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{1.2:3.4}' | python -mjson.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

注意 : json 是 YAML 1.2d的子集,是这个模块的默认设定产生的,这个模块也可以被用作YML 串.
基本用法
json.dump()
json.dumps()
json.load()
json.loads()
后续补充


编码与解码
类json.JSONDecoder()
后续补充


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值