Search notes:

Python standard library: json

Parsing JSON text

A file-like object that contains JSON data can be parsed into a json object using load().
loads() is identical to load() except that the data is contained in a str, bytes or bytearray instance.
This script demonstrates both load() and loads():
import json

#
#   Reading json data from a string
#
d = json.loads ('''

  {
    "foo":{
       "42":"forty-two",
       "8" :"eight"
    },
    "bar":[
       {"key":"1"},
       {"key":"2"},
       {"key":"3"},
       {"key":"4"}
    ]
  }
  
''')

print(d['foo']['42']) # forty-two

# -------------------------------
#
#  Reading json data from a file
#

json_file=open('file.json')
f=json.load(json_file)
print(f[2][1])            # Yes
print(f[3]['foo'])        # word
Github repository about-python, path: /standard-library/json/script.py
This is the file that the script reads (file.json):
[
  1,
  2,
  [ 3, "Yes", 5 ],
  {
    "one": "number",
    "foo": "word"
  } 
]
Github repository about-python, path: /standard-library/json/file.json

Turning Python objects into JSON text

json.dumps(obj) returns a JSON-string representation of the object obj.
json.dump(obj, fs) writes such a representation into a file that was opened with open().
import json

obj = {
   'num':  42,
   'txt': 'Hello world',
   'lst': [ 1, 2, 3 ],
   'dct': { 'k1': 'one', 'k2': 'two'}
}

print(json.dumps(obj))
#
#  {"num": 42, "txt": "Hello world", "lst": [1, 2, 3], "dct": {"k1": "one", "k2": "two"}}

with open('dumped.json', 'w') as df:
    json.dump(obj, df)
Github repository about-python, path: /standard-library/json/dump.py

See also

The pickle module allows to serialize an arbitrarily complex object.
Other standard library modules, such as
Parsing float values in JSON objects.

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758185884, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/standard-library/json/index(124): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78