最簡單的使用方法是:
>>> 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('//')) "http://" >>> 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數(shù)據(jù)不易于查看,所有數(shù)據(jù)都顯示在一行上面。如果我們需要格式更加良好的json數(shù)據(jù),我們可以如下使用方法:
>>> 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本身的數(shù)據(jù)解析,請放心使用。
解析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('"http://"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數(shù)據(jù)格式為:
[{"manageTotal":"管理"}] 注意:json不支持單引號
新聞熱點
疑難解答
圖片精選