JSON

https://d33wubrfki0l68.cloudfront.net/c17fde1edf579b1e6d946ab32d8a1c29e6bcf9ba/e431d/_images/33928819683_97b5c6a184_k_d.jpg
The json library can parseJSON from strings or files. The library parses JSON into a Python dictionaryor list. It can also convert Python dictionaries or lists into JSON strings.

Parsing JSON

Take the following string containing JSON data:

  1. json_string = '{"first_name": "Guido", "last_name":"Rossum"}'

It can be parsed like this:

  1. import json
  2. parsed_json = json.loads(json_string)

and can now be used as a normal dictionary:

  1. print(parsed_json['first_name'])
  2. "Guido"

You can also convert the following to JSON:

  1. d = {
  2. 'first_name': 'Guido',
  3. 'second_name': 'Rossum',
  4. 'titles': ['BDFL', 'Developer'],
  5. }
  6.  
  7. print(json.dumps(d))
  8. '{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}'

simplejson

The json library was added to Python in version 2.6.If you’re using an earlier version of Python, thesimplejson library isavailable via PyPI.

simplejson mimics the json standard library. It is available so that developersthat use older versions of Python can use the latest features available in thejson lib.

You can start using simplejson when the json library is not available byimporting simplejson under a different name:

  1. import simplejson as json

After importing simplejson as json, the above examples will all work as if youwere using the standard json library.

原文: https://docs.python-guide.org/scenarios/json/