{"account": 100, "name": "Jones", "balance": 24.98}
JSON arrays, like Python lists, are comma-separated values in square brackets.
[100, 200, 300]
Values in JSON objects and arrays can be:
true
or false
null
(like None
in Python)json
¶json
module enables you to convert objects to JSON (JavaScript Object Notation) text format'accounts'
with its associated value being a list of dictionaries representing two accountsaccounts_dict = {'accounts': [
{'account': 100, 'name': 'Jones', 'balance': 24.98},
{'account': 200, 'name': 'Doe', 'balance': 345.67}]}
json
module’s dump
function serializes the dictionary accounts_dict
into the fileimport json
with open('accounts.json', 'w') as accounts:
json.dump(accounts_dict, accounts)
{"accounts":
[{"account": 100, "name": "Jones", "balance": 24.98},
{"account": 200, "name": "Doe", "balance": 345.67}]}
json
module’s load
function reads entire JSON contents of its file object argument and converts the JSON into a Python objectwith open('accounts.json', 'r') as accounts:
accounts_json = json.load(accounts)
accounts_json
accounts_json['accounts']
accounts_json['accounts'][0]
accounts_json['accounts'][1]
json
module’s dumps
function (dumps
is short for “dump string”) returns a Python string representation of an object in JSON formatindent
keyword argument, the string contains newline characters and indentation for pretty printingindent
with the dump
function when writing to a filewith open('accounts.json', 'r') as accounts:
print(json.dumps(json.load(accounts), indent=4))
©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.
DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.