python数据封装json格式数据

yipeiwu_com6年前Python基础

最简单的使用方法是:

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

一般情况下:

>>> import simplejson as json 
>>> obj = [1,2,3,{'4': 5, '6': 7}] 
>>> json.dumps(obj, separators=(',', ':'), sort_keys=True) 
'[1,2,3,{"4":5,"6":7}]' 

这样得到的json数据不易于查看,所有数据都显示在一行上面。如果我们需要格式更加良好的json数据,我们可以如下使用方法:

>>> import simplejson as json 
>>> 
>>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4) 
>>> s 
'{\n  "4": 5,\n  "6": 7\n}' 
>>> print('\n'.join([l.rstrip() for l in s.splitlines()])) 
{ 
  "4": 5, 
  "6": 7 
} 
>>> 

\n不会影响json本身的数据解析,请放心使用。

解析json格式的字符串:

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

读取并解析json格式文件

def edit(request): 
  filepath = os.path.join(os.path.dirname(__file__),'rights.json') 
  content = open(filepath).read().decode('utf-8') 
  rights = simplejson.loads(content) 
  print rights 
  print rights[0]['manageTotal'] 

json数据格式为:

[{"manageTotal":"管理"}] 

注意:json不支持单引号

相关文章

基于DataFrame改变列类型的方法

今天用numpy 的linalg.det()求矩阵的逆的过程中出现了一个错误: TypeError: No loop matching the specified signature...

分析python切片原理和方法

分析python切片原理和方法

使用索引获取列表的元素(随机读取) 列表元素支持用索引访问,正向索引从0开始 colors=["red","blue","green"] colors[0] =="red"...

python 迭代器和iter()函数详解及实例

python中迭代器和iter()函数 迭代器为类序列对象提供了一个类序列的接口。python的迭代无缝地支持序列对象,而且它还允许程序员迭代非序列类型,包括用户定义的对象。迭代器用起...

pytorch自定义二值化网络层方式

任务要求: 自定义一个层主要是定义该层的实现函数,只需要重载Function的forward和backward函数即可,如下: import torch from torch.aut...

Python中@property的理解和使用示例

本文实例讲述了Python中@property的理解和使用。分享给大家供大家参考,具体如下: 重看狗书,看到对User表定义的时候有下面两行 @property def pa...