Python Data encapsulation json format data, python encapsulation json format
The simplest method is:
>>> 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"]'
Generally:
>>> 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 data is not easy to view. All data is displayed on a row. If we need better json data format, we can use the following method:
>>> 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 does not affect json data parsing. Please feel free to use it.
Parse a json string:
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
Read and parse json files
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 data format:
[{"ManageTotal": "management"}]
Note: json does not support single quotes.