Software Development Python

Understanding JSON Dump in Python

Understanding JSON Dump in Python

Introduction

The object literal syntax of the JavaScript programming language served as the model for JavaScript Object Notation.

Python's "json" module has built-in support for JSON documents. Due to its user-friendliness, interoperability with APIs, queries, and data streamlining abilities, it is quite popular. The json.dumps() function makes it simple to obtain a JSON string from a Python dictionary object.

This article will provide you an example-based introduction to the json.dumps() technique.

Understanding JSON

To begin, let us study the JSON structure first. Nothing has to be downloaded; the JSON module should already be installed on Python 3.x.

import json

{
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Alice",
            "age": 6
        },
        {
            "firstName": "Bob",
            "age": 8
        }
    ]
}

As seen above, JSON allows nested lists, objects, and primitive kinds like strings and integers.

The function json.dump() (without the "s" in "dump") is used to create a file containing serialized Python objects in JSON format.

Python JSON Encoding and serialization using dump and dumps

Applications and Useful Scenarios

  1. Create JSON-formatted data by encoding Python serialized objects.
  2. Create a JSON file with Python objects by encoding and writing them there
  3. Avoid encoding non-basic types when using JSON
  4. Save file space by using compact encoding.
  5. When encoding JSON, deal with non-ASCII data.

Syntax

json.dump(dictionary, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None)

Let's examine the inputs that this function requires.

  • The object you wish to serialise into JSON is called obj, and it is a Python object.
  • When writing data in JSON format into a file, a file pointer, or fp, is utilized. Fp.write() must handle string input since the Python json module always creates string objects, never bytes objects.
  • The keys in a dict that are not of a fundamental type (str, int, float, bool, or None) will not raise a TypeError if skipkeys is set to true (the default value is False). When converting your dictionary to JSON, for instance, if one of the dictionary keys is a unique Python object, that key will be removed.
  • Non-ASCII characters are ensured to be escaped in the output if ensure ascii is set to true (the default). Those characters won't be shown if ascii is false.
  • Their JavaScript counterparts (NaN, Infinity, and -Infinity) will be utilised since allow nan is set to True by default. Serializing out-of-range float values will result in a ValueError if False (nan, inf, -inf).
  • To make JSON more understandable, it is pretty-printed using the indent parameter. The default value is (', ', ': '). Use (',', ':') to remove whitespace to produce the most condensed JSON representation possible.
  • Dictionary output is sorted by key if sort keys is true (the default value is False).

Example:

In this demonstration, we will write the Python dictionary to a file in a JSON format. A JSON file must be understandable and well-organized if the user desires to read it, making it easier for everyone who uses it to comprehend the data's structure.

import json

mydictionary= {
    "name": "jane doe",
    "salary": 9000,
    "skills": ["Machine Learning", "Raspberry Pi", "Web Development"],
    "email": "JaneDoe@pynative.com"
}

with open("developerPrettyPrint.json", "w") as write_file:
    json.dump(mydictionary, write_file, indent=4, separators=(", ", ": "), sort_keys=False)
print("JSON file written")

write your code here: Coding Playground

Output

File after writing prettyprinted JSON data

In this article you learned that Python's "json" module has built-in support for JSON documents. Due to its user-friendliness, interoperability with APIs, queries, and data streamlining abilities, it is quite popular. The Python json.dumps() method allows us to easily convert a dictionary object into a JSON string.