w3resource

Python JSON Module tutorial

Encode Python objects as JSON strings, and decode JSON strings into Python objects

In Python, the json module provides an API similar to convert in-memory Python objects to a serialized representation known as JavaScript Object Notation (JSON) and vice-a-versa.

Encode Python objects as JSON strings

Basic Usage :


json.dump(obj, fp,
                  skipkeys=False,
                  ensure_ascii=True,
  		  check_circular=True,
		  allow_nan=True,
		  cls=None,
		  indent=None,
		  separators=None,
		  default=None,
		  sort_keys=False, **kw)

The above method serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) using the following conversion table.

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

Options :

  • The default value of skipkeys is False. If skipkeys is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
  • The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
  • If ensure_ascii is True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is False, these characters will be output as-is.
  • The default value of check_circular is True. If check_circular is False, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError.
  • The default value of allow_nan is True. If allow_nan is False, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance with the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
  • If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
  • Use (',', ': ') as default if indent is not None.
  • The default value of sort_keys is False. If sort_keys is True, then the output of dictionaries will be sorted by key.

Examples : Python Dictionaries to JSON strings

Code :


import json
student = {"101":{"class":'V', "Name":'Rohit',  "Roll_no":7},
           "102":{"class":'V', "Name":'David',  "Roll_no":8},
           "103":{"class":'V', "Name":'Samiya', "Roll_no":12}}
print(json.dumps(student));

Output:

{"103": {"class": "V", "Name": "Samiya", "Roll_no": 12}, 
"102": {"class": "V", "Name": "David", "Roll_no": 8}, 
"101": {"class": "V", "Name": "Rohit", "Roll_no": 7}}

Examples : Python Dictionaries to JSON strings (sorted by key)

Code :


import json
student = {"101":{"class":'V', "Name":'Rohit',  "Roll_no":7},
           "102":{"class":'V', "Name":'David',  "Roll_no":8},
           "103":{"class":'V', "Name":'Samiya', "Roll_no":12}}
print(json.dumps(student, sort_keys=True));

Output:

{"101": {"Name": "Rohit", "Roll_no": 7, "class": "V"}, 
"102": {"Name": "David", "Roll_no": 8, "class": "V"}, 
"103": {"Name": "Samiya", "Roll_no": 12, "class": "V"}}

Examples : Python tuple to JSON array

Code :


import json
tup1 = 'Red', 'Black', 'White';
print(json.dumps(tup1));

Output:

["Red", "Black", "White"]

Examples : Python list to JSON array

Code :


import json
list1 = [5, 12, 13, 14];
print(json.dumps(list1));

Output :

[5, 12, 13, 14]

Examples : Python string to JSON string

Code :


import json
string1 = 'Python and JSON';
print(json.dumps(string1));

Output:

"Python and JSON"

Examples : Python Boolean values to JSON Boolean values

Code :


import json
x = True;
print(json.dumps(x));

Output:

true

Examples : Python int, float, int- & float-derived Enums to JSON number

Code :


import json
x = -456;
y = -1.406;
z =  2.12e-10
print(json.dumps(x));
print(json.dumps(y));
print(json.dumps(z));

Output:

-456
-1.406
2.12e-10

Decode JSON strings into Python objects

Basic Usage :


json.load(fp, 
          cls=None, 
		  object_hook=None, 
		  parse_float=None, 
		  parse_int=None, 
		  parse_constant=None, 
		  object_pairs_hook=None, **kw)

The above method deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using the following conversion table.

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

 

Options :

  • The default value of skipkeys is False. If skipkeys is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
  • The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.
  • If ensure_ascii is True (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is False, these characters will be output as-is.
  • The default value of check_circular is True. If check_circular is False, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError.
  • The default value of allow_nan is True. If allow_nan is False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance with the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
  • If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
  • Use (',', ': ') as default if indent is not None.
  • default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
  • The default value of sort_keys is False. If sort_keys is True, then the output of dictionaries will be sorted by key.

Examples : JSON strings to Python Dictionaries

Code :


import json
json_data = '{"103": {"class": "V", "Name": "Samiya", "Roll_n": 12}, "102": {"class": "V", "Name": "David", "Roll_no": 8}, "101": {"class": "V", "Name": "Rohit", "Roll_no": 7}}';
print(json.loads(json_data));

Output:

{"103": {"class": "V", "Name": "Samiya", "Roll_no": 12}, 
"102": {"class": "V", "Name": "David", "Roll_no": 8}, 
"101": {"class": "V", "Name": "Rohit", "Roll_no": 7}}

Examples : JSON array Python tuple

Code :

import json
Json_array = ["Red", "Black", "White"] print(json.dumps(Json_array));

Output:

["Red", "Black", "White"]

Examples : Python list to JSON array

Code:


import json
list1 = [5, 12, 13, 14];
print(json.dumps(list1));

Output:

[5, 12, 13, 14]

Examples : JSON string to Python string

Code :


import json 
Json_string = "Python and JSON" 
print(json.dumps(Json_string));

Output:

"Python and JSON"

Python Version : 3.4

Previous: Working with JSON and JavaScript
Next: Working with JSONPath and JavaScript