python数据封装json格式数据
最简单的使用方法是:
>>> 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不支持单引号
相关推荐
Plant 2020-05-31
liulufei 2020-05-09
hygbuaa 2020-04-30
TreasureZ 2020-02-22
russle 2016-11-18
ajaxtony 2019-10-28
popohopo 2013-03-02
xyzxiafancai 2017-04-21
russle 2016-11-18
cyydjt 2013-07-09
智小星 2019-06-28
simon曦 2010-10-20
XTUxiaoxin 2014-02-28
86193951 2019-06-18
aspshipin 2013-10-06
xianzhe 2019-06-21
simon曦 2007-07-11