Python Data encapsulation json format data, python encapsulation json format

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.