python数据封装json格式数据

时间:2022-06-16 03:26:20

最简单的使用方法是:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> 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"]'

一般情况下:

?
1
2
3
4
>>> 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数据,我们可以如下使用方法:

?
1
2
3
4
5
6
7
8
9
10
11
>>> 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格式的字符串:

?
1
2
3
4
5
6
7
8
9
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格式文件

?
1
2
3
4
5
6
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数据格式为:

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

注意:json不支持单引号