{"id":1082,"date":"2024-05-30T10:28:15","date_gmt":"2024-05-30T10:28:15","guid":{"rendered":"https:\/\/www.ipway.com\/blog\/?p=1082"},"modified":"2024-05-30T10:28:15","modified_gmt":"2024-05-30T10:28:15","slug":"json-load-in-python","status":"publish","type":"post","link":"https:\/\/www.ipway.com\/blog\/json-load-in-python\/","title":{"rendered":"Parsing Json.load data in Python"},"content":{"rendered":"\n<p>JSON (JavaScript Object Notation) has become a player in the field of data exchange because of its straightforwardness and ease of understanding. Python, an used programming language offers strong capabilities for managing JSON data. <\/p>\n\n\n\n<p>This piece explores the details of processing JSON data in Python with a focus on the json.load function and other related methods. We will discuss approaches, to converting JSON data into Python objects and back again aiming to provide a thorough grasp of these fundamental skills.<\/p>\n\n\n<div class=\"ub_table-of-contents\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" id=\"ub_table-of-contents-d9bdfb40-01dd-4e6d-8ff3-78ab185e49aa\" data-initiallyhideonmobile=\"false\"\n                    data-initiallyshow=\"true\"><div class=\"ub_table-of-contents-header-container\"><div class=\"ub_table-of-contents-header\">\n                    <div class=\"ub_table-of-contents-title\">Parsing Json.load data in Python<\/div><\/div><\/div><div class=\"ub_table-of-contents-extra-container\"><div class=\"ub_table-of-contents-container ub_table-of-contents-1-column \"><ul><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#0-what-is-json->What Is JSON?<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#1-what-is-jsonload->What is json.load?<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#2-converting-json-string-to-python-object->Converting JSON string to Python object<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#3-converting-json-file-to-python-object->Converting JSON file to Python object<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#4-writing-python-object-to-a-json-file->Writing Python object to a JSON file<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#5-converting-custom-python-objects-to-json-objects->Converting Custom Python Objects to JSON Objects<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#6-creating-python-class-objects-from-json-objects->Creating Python class objects from JSON objects<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#7-loading-vs-dumping->Loading vs dumping<\/a><\/li><li><a href=https:\/\/www.ipway.com\/blog\/json-load-in-python\/#8-conclusion->Conclusion<\/a><\/li><\/ul><\/div><\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-is-json-\"><strong>What Is JSON?<\/strong><\/h2>\n\n\n\n<p>JSON, short for JavaScript Object Notation is a data format that is readable and writable, for humans and easy to process and create for machines. It relies on two structures: <\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>A set of name and value combinations, commonly known as an object, dictionary, hash table or associative array.<\/li>\n\n\n\n<li>A structured collection of values often known as an array, list or sequence.<\/li>\n<\/ol>\n\n\n\n<p><strong>Example of JSON:<\/strong><\/p>\n\n\n\n<p>Here&#8217;s an example of JSON data representing a simple object with name-value pairs and an array: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"name\": \"Alice\",\n  \"age\": 30,\n  \"is_student\": false,\n  \"courses\": &#91;\"Math\", \"Science\", \"Art\"]\n}\n<\/code><\/pre>\n\n\n\n<p><strong>In this example:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>name<\/code>, <code>age<\/code>, and <code>is_student<\/code> are keys with corresponding values.<\/li>\n\n\n\n<li><code>courses<\/code> is a key with an array of values.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1680\" height=\"1120\" src=\"https:\/\/www.ipway.com\/blog\/wp-content\/uploads\/2024\/05\/json.load-python.jpg\" alt=\"json.load\" class=\"wp-image-1093\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-what-is-jsonload-\"><strong>What is json.load?<\/strong> <\/h2>\n\n\n\n<p>The json.load function in <a href=\"https:\/\/www.python.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a> is essential for handling JSON data saved in files. It helps convert a JSON file into a <a href=\"https:\/\/www.python.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a> object, like a dictionary or list. Lets dive into how json.load functions and why it matters:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Reading from a File<\/strong>: The primary function of json.load is to extract information directly from a file object. The file must be opened in read mode (&#8216;r&#8217;). Must include correctly structured JSON data.<\/li>\n\n\n\n<li><strong>Deserialization Process<\/strong>: Converting data into native Python data types is what deserialization entails. When json.load processes JSON data it links JSON objects to Python dictionaries, JSON arrays to Python lists JSON strings to Python strings and JSON numbers to Python integers or floats. This simplifies. Manipulating the data, in your Python code.<\/li>\n\n\n\n<li><strong>Basic Usage<\/strong>:<\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Open the file containing JSON data<\/li>\n\n\n\n<li>Use <code>json.load<\/code> to read the JSON data from the file and convert it into a Python object.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\n# Sample JSON content in 'data.json':\n# {\n#     \"name\": \"Alice\",\n#     \"age\": 30,\n#     \"is_student\": false,\n#     \"courses\": &#91;\"Math\", \"Science\", \"Art\"]\n# }\n\n# Open the JSON file\nwith open('data.json', 'r') as file:\n    # Load JSON data into a Python object\n    data = json.load(file)\n\n# Print the Python object\nprint(data)  # Output: {'name': 'Alice', 'age': 30, 'is_student': False, 'courses': &#91;'Math', 'Science', 'Art']}\n<\/code><\/pre>\n\n\n\n<p>4. <strong>Error Handling<\/strong>: When using json.load it&#8217;s important to address any errors, particularly the JSONDecodeError that may occur if the file contains invalid JSON. This helps your program effectively manage flawed or damaged JSON data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\ntry:\n    with open('data.json', 'r') as file:\n        data = json.load(file)\nexcept json.JSONDecodeError as e:\n    print(f\"Error decoding JSON: {e}\")\n<\/code><\/pre>\n\n\n\n<p>5. <strong>Optional Parameters<\/strong>: <\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>cls<\/strong>: Describes a JSON decoding class. By default JSONDecoder is employed.<\/li>\n\n\n\n<li><strong>object_hook<\/strong>: A feature that can convert the JSON data into a Python object. This function is invoked for each decoded JSON object.<\/li>\n\n\n\n<li><strong>parse_float<\/strong>: When required it will be referred to with the string of each decimal number, for decoding.<\/li>\n\n\n\n<li><strong>parse_int<\/strong>: If needed it will be referred to as the string containing each JSON integer, for decoding.<\/li>\n\n\n\n<li><strong>parse_constant<\/strong>: If required it will be referred to by one of the following terms; &#8216;NaN&#8217; &#8216;Infinity&#8217; or&#8217; Infinity&#8217;.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\nclass Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n\ndef decode_person(dct):\n    if \"name\" in dct and \"age\" in dct:\n        return Person(dct&#91;\"name\"], dct&#91;\"age\"])\n    return dct\n\nwith open('data.json', 'r') as file:\n    person = json.load(file, object_hook=decode_person)\n\nprint(person.__dict__)\n<\/code><\/pre>\n\n\n\n<p>By grasping the concept and using the json.load method you can effectively. Interpret JSON data from files making it easier to exchange and work with data in your <a href=\"https:\/\/www.python.org\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python<\/a> programs. This method comes in handy when dealing with configuration files data formats, for sharing information or JSON formatted API responses.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-converting-json-string-to-python-object-\"><strong>Converting JSON string to Python object<\/strong><\/h2>\n\n\n\n<p>When dealing with data exchange formats it&#8217;s quite common to convert a JSON string into a Python object. In Python you can accomplish this by using the json.loads() function found in the json module. Let me walk you through how this procedure unfolds step, by step:<\/p>\n\n\n\n<p><strong>Import the JSON Module<\/strong>: Before you can use <code>json.loads()<\/code>, you need to import the <code>json<\/code> module.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n<\/code><\/pre>\n\n\n\n<p><strong>JSON String<\/strong>: Make sure you have your JSON string prepared. The string should follow the JSON format and be enclosed within double quotation marks.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json_string = '{\"name\": \"Alice\", \"age\": 30, \"is_student\": false, \"courses\": &#91;\"Math\", \"Science\", \"Art\"]}'\n<\/code><\/pre>\n\n\n\n<p><strong>Use <code>json.loads()<\/code><\/strong>: This feature reads through the JSON string. Transforms it into a Python dictionary or other suitable data structures, in Python.<\/p>\n\n\n\n<p><strong>Output<\/strong>: The Python object that is generated can be utilized similarly to a dictionary or list, in Python.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(python_obj)\n# Output: {'name': 'Alice', 'age': 30, 'is_student': False, 'courses': &#91;'Math', 'Science', 'Art']}\n<\/code><\/pre>\n\n\n\n<p><strong>Example in Detail<\/strong><\/p>\n\n\n\n<p>Think about a JSON string that shows a users profile. This string contains types of data, like text, numbers, true\/false values and lists.<\/p>\n\n\n\n<p><strong>Step-by-Step Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json_string = '''\n{\n    \"username\": \"john_doe\",\n    \"active\": true,\n    \"email\": \"john.doe@example.com\",\n    \"roles\": &#91;\"admin\", \"user\"],\n    \"age\": 28\n}\n'''<\/code><\/pre>\n\n\n\n<p><strong>Convert to Python Object<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\n# Parsing JSON string\nuser_profile = json.loads(json_string)\n<\/code><\/pre>\n\n\n\n<p><strong>Accessing Data<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(user_profile&#91;\"username\"])  # Output: john_doe\nprint(user_profile&#91;\"active\"])    # Output: True\nprint(user_profile&#91;\"email\"])     # Output: john.doe@example.com\nprint(user_profile&#91;\"roles\"])     # Output: &#91;'admin', 'user']\nprint(user_profile&#91;\"age\"])       # Output: 28\n<\/code><\/pre>\n\n\n\n<p><strong>Handling Errors<\/strong><\/p>\n\n\n\n<p>Dealing with errors that may arise during the conversion process is crucial. One typical issue is encountering a json.JSONDecodeError signaling that the JSON string lacks formatting.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try:\n    python_obj = json.loads(json_string)\nexcept json.JSONDecodeError as e:\n    print(f\"Error decoding JSON: {e}\")\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-converting-json-file-to-python-object-\"><strong>Converting JSON file to Python object<\/strong><\/h2>\n\n\n\n<p>Dealing with errors that may arise during the conversion process is crucial. One typical issue is encountering a json.JSONDecodeError signaling that the JSON string lacks formatting.<\/p>\n\n\n\n<p>Converting a Python object to a JSON string is a process known as serialization or JSON encoding. This is typically done using the <code>json.dumps()<\/code> function from the <code>json<\/code> module. Here\u2019s a detailed breakdown of how this conversion works:<\/p>\n\n\n\n<p><strong>Import the JSON Module<\/strong>: Before using <code>json.dumps()<\/code>, import the <code>json<\/code> module.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n<\/code><\/pre>\n\n\n\n<p><strong>Python Object<\/strong>: Prepare your Python object, which could be a dictionary, list, tuple, string, etc.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python_obj = {\n    \"name\": \"Alice\",\n    \"age\": 30,\n    \"is_student\": False,\n    \"courses\": &#91;\"Math\", \"Science\", \"Art\"]\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Use <code>json.dumps()<\/code><\/strong>: This function serializes the Python object into a JSON-formatted string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json_string = json.dumps(python_obj)\n<\/code><\/pre>\n\n\n\n<p><strong>Output<\/strong>: The resulting JSON string can be printed or used for data exchange.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>print(json_string)\n# Output: '{\"name\": \"Alice\", \"age\": 30, \"is_student\": false, \"courses\": &#91;\"Math\", \"Science\", \"Art\"]}'\n<\/code><\/pre>\n\n\n\n<p><strong>Example in Detail<\/strong><\/p>\n\n\n\n<p><strong>Python Dictionary<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>book = {\n    \"title\": \"To Kill a Mockingbird\",\n    \"author\": \"Harper Lee\",\n    \"published_year\": 1960,\n    \"genres\": &#91;\"Fiction\", \"Drama\"]\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Convert to JSON String<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\n# Serializing Python object to JSON string\njson_string = json.dumps(book)\n<\/code><\/pre>\n\n\n\n<p><strong>Formatted Output<\/strong>: To make the JSON string more readable, you can use the <code>indent<\/code> parameter to add indentation.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json_string = json.dumps(book, indent=4)\nprint(json_string)\n<\/code><\/pre>\n\n\n\n<p><strong>Handling Complex Objects<\/strong><\/p>\n\n\n\n<p>For custom Python objects, you need to define a custom encoder by subclassing <code>json.JSONEncoder<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Book:\n    def __init__(self, title, author, year, genres):\n        self.title = title\n        self.author = author\n        self.year = year\n        self.genres = genres\n\nclass BookEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Book):\n            return obj.__dict__\n        return super().default(obj)\n\nbook = Book(\"To Kill a Mockingbird\", \"Harper Lee\", 1960, &#91;\"Fiction\", \"Drama\"])\njson_string = json.dumps(book, cls=BookEncoder)\nprint(json_string)\n<\/code><\/pre>\n\n\n\n<p>When you change Python elements into JSON text you enable the transfer of information between systems or parts simplifying the storage, transmission and handling of data in a standardized way. This step is crucial, for programs that engage with services, APIs or setup files.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-writing-python-object-to-a-json-file-\"><strong>Writing Python object to a JSON file<\/strong><\/h2>\n\n\n\n<p>Converting a Python object into a JSON file is referred to as serialization or encoding. To achieve this you can utilize the json.dump() function found in the json module. Let me walk you through the steps involved in completing this process:<\/p>\n\n\n\n<p><strong>Import the JSON Module<\/strong>: Start by importing the <code>json<\/code> module.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n<\/code><\/pre>\n\n\n\n<p><strong>Prepare the Python Object<\/strong>: This object can be a dictionary, list, or any serializable Python data structure.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python_obj = {\n    \"name\": \"Alice\",\n    \"age\": 30,\n    \"is_student\": False,\n    \"courses\": &#91;\"Math\", \"Science\", \"Art\"]\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Use <code>json.dump()<\/code><\/strong>: This function serializes the Python object and writes it to a file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>with open('data.json', 'w') as file:\n    json.dump(python_obj, file)\n<\/code><\/pre>\n\n\n\n<p><strong>Adding Indentation<\/strong>: To enhance the readability of the JSON file you can improve its format by incorporating indentation through the utilization of the parameter.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>with open('data.json', 'w') as file:\n    json.dump(python_obj, file, indent=4)\n<\/code><\/pre>\n\n\n\n<p><strong>Example in Detail<\/strong><\/p>\n\n\n\n<p><strong>Step-by-Step Example:<\/strong><\/p>\n\n\n\n<p><strong>Python Dictionary<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>book = {\n    \"title\": \"To Kill a Mockingbird\",\n    \"author\": \"Harper Lee\",\n    \"published_year\": 1960,\n    \"genres\": &#91;\"Fiction\", \"Drama\"]\n}\n<\/code><\/pre>\n\n\n\n<p><strong>Write to JSON File<\/strong>: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\n# Open the file in write mode\nwith open('book.json', 'w') as file:\n    # Serialize the Python object to JSON and write to the file\n    json.dump(book, file)\n<\/code><\/pre>\n\n\n\n<p><strong>Formatted Output<\/strong>: <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>with open('book.json', 'w') as file:\n    json.dump(book, file, indent=4)\n<\/code><\/pre>\n\n\n\n<p><strong>Handling Custom Objects<\/strong><\/p>\n\n\n\n<p>When creating Python objects you must craft a personalized encoder by extending json.JSONEncoder.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Book:\n    def __init__(self, title, author, year, genres):\n        self.title = title\n        self.author = author\n        self.year = year\n        self.genres = genres\n\nclass BookEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Book):\n            return obj.__dict__\n        return super().default(obj)\n\nbook = Book(\"To Kill a Mockingbird\", \"Harper Lee\", 1960, &#91;\"Fiction\", \"Drama\"])\nwith open('book.json', 'w') as file:\n    json.dump(book, file, cls=BookEncoder, indent=4)\n<\/code><\/pre>\n\n\n\n<p>Storing and sharing data in a format that is readable by both humans and machines can be done effortlessly by saving Python objects to a JSON file. This method comes in handy for tasks like preserving configurations ensuring data persistence and facilitating data transfer, among systems or components.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-converting-custom-python-objects-to-json-objects-\"><strong>Converting Custom Python Objects to JSON Objects<\/strong><\/h2>\n\n\n\n<p>When you want to convert your Python objects into JSON format you&#8217;ll need to follow a special serialization method because the standard JSON encoder doesn&#8217;t support custom classes. Below is an, in depth explanation of how you can make this conversion:<\/p>\n\n\n\n<p><strong>Define a Custom Class<\/strong>: Create a Python class for your custom objects.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n<\/code><\/pre>\n\n\n\n<p><strong>Create a Custom JSON Encoder<\/strong>: Extend the json.JSONEncoder. Customize the default method to define the conversion of the custom object into a format compatible, with JSON.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\nclass PersonEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Person):\n            return obj.__dict__\n        return super().default(obj)\n<\/code><\/pre>\n\n\n\n<p><strong>Serialize Custom Object to JSON<\/strong>: You can employ json.dumps() alongside an encoder to transform the customized object into a JSON string.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>person = Person(\"Alice\", 30)\njson_string = json.dumps(person, cls=PersonEncoder)\nprint(json_string)  # Output: {\"name\": \"Alice\", \"age\": 30}\n<\/code><\/pre>\n\n\n\n<p>If you have a Book class and need to change the instances of this class into JSON objects.<\/p>\n\n\n\n<p><strong>Define the Custom Class<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Book:\n    def __init__(self, title, author, published_year, genres):\n        self.title = title\n        self.author = author\n        self.published_year = published_year\n        self.genres = genres\n<\/code><\/pre>\n\n\n\n<p><strong>Create the Custom JSON Encoder<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class BookEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Book):\n            return {\n                \"title\": obj.title,\n                \"author\": obj.author,\n                \"published_year\": obj.published_year,\n                \"genres\": obj.genres\n            }\n        return super().default(obj)\n<\/code><\/pre>\n\n\n\n<p><strong>Serialize the Custom Object<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>book = Book(\"To Kill a Mockingbird\", \"Harper Lee\", 1960, &#91;\"Fiction\", \"Drama\"])\njson_string = json.dumps(book, cls=BookEncoder, indent=4)\nprint(json_string)\n<\/code><\/pre>\n\n\n\n<p><strong>Handling Nested Custom Objects<\/strong><\/p>\n\n\n\n<p>If your personalized items include personalized items it&#8217;s important to make sure that the encoder can manage these nested objects too.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Publisher:\n    def __init__(self, name, founded):\n        self.name = name\n        self.founded = founded\n\nclass Book:\n    def __init__(self, title, author, published_year, genres, publisher):\n        self.title = title\n        self.author = author\n        self.published_year = published_year\n        self.genres = genres\n        self.publisher = publisher\n\nclass ComplexEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, Book):\n            return {\n                \"title\": obj.title,\n                \"author\": obj.author,\n                \"published_year\": obj.published_year,\n                \"genres\": obj.genres,\n                \"publisher\": obj.publisher.__dict__\n            }\n        if isinstance(obj, Publisher):\n            return obj.__dict__\n        return super().default(obj)\n\npublisher = Publisher(\"J.B. Lippincott &amp; Co.\", 1836)\nbook = Book(\"To Kill a Mockingbird\", \"Harper Lee\", 1960, &#91;\"Fiction\", \"Drama\"], publisher)\njson_string = json.dumps(book, cls=ComplexEncoder, indent=4)\nprint(json_string)\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-creating-python-class-objects-from-json-objects-\"><strong>Creating Python class objects from JSON objects<\/strong><\/h2>\n\n\n\n<p>Converting JSON data back into Python objects also known as deserialization involves the process of creating Python class objects from objects. This can be done by utilizing the json.loads() function along, with the parameter, which enables customized handling of JSON objects.<\/p>\n\n\n\n<p><strong>Define the Custom Class<\/strong>: Create a Python class to represent your custom objects<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Person:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n<\/code><\/pre>\n\n\n\n<p><strong>Define a Function for Object Hook<\/strong>: This function will convert dictionaries to instances of the custom class.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def decode_person(dct):\n    if \"name\" in dct and \"age\" in dct:\n        return Person(dct&#91;\"name\"], dct&#91;\"age\"])\n    return dct\n<\/code><\/pre>\n\n\n\n<p><strong>Use <code>json.loads()<\/code> with <code>object_hook<\/code><\/strong>: Deserialize the JSON string into a custom Python object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\nperson = json.loads(json_string, object_hook=decode_person)\nprint(person.name)  # Output: Alice\nprint(person.age)   # Output: 30\n<\/code><\/pre>\n\n\n\n<p>Imagine a situation where you come across a JSON string that describes a book and you wish to transform this information into an object of a Book class.<\/p>\n\n\n\n<p><strong>Define the Custom Class<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Book:\n    def __init__(self, title, author, published_year, genres):\n        self.title = title\n        self.author = author\n        self.published_year = published_year\n        self.genres = genres\n<\/code><\/pre>\n\n\n\n<p><strong>Define the Object Hook Function<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def decode_book(dct):\n    if \"title\" in dct and \"author\" in dct and \"published_year\" in dct and \"genres\" in dct:\n        return Book(dct&#91;\"title\"], dct&#91;\"author\"], dct&#91;\"published_year\"], dct&#91;\"genres\"])\n    return dct\n<\/code><\/pre>\n\n\n\n<p><strong>Deserialize the JSON String<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>json_string = '''\n{\n    \"title\": \"To Kill a Mockingbird\",\n    \"author\": \"Harper Lee\",\n    \"published_year\": 1960,\n    \"genres\": &#91;\"Fiction\", \"Drama\"]\n}\n'''\nbook = json.loads(json_string, object_hook=decode_book)\nprint(book.title)          # Output: To Kill a Mockingbird\nprint(book.author)         # Output: Harper Lee\nprint(book.published_year) # Output: 1960\nprint(book.genres)         # Output: &#91;'Fiction', 'Drama']\n<\/code><\/pre>\n\n\n\n<p><strong>Handling Nested Custom Objects<\/strong><\/p>\n\n\n\n<p>When dealing with JSON data containing custom objects it is crucial to make sure that the object hook function is capable of managing the nested structures effectively.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Publisher:\n    def __init__(self, name, founded):\n        self.name = name\n        self.founded = founded\n\nclass Book:\n    def __init__(self, title, author, published_year, genres, publisher):\n        self.title = title\n        self.author = author\n        self.published_year = published_year\n        self.genres = genres\n        self.publisher = publisher\n\ndef decode_complex(dct):\n    if \"name\" in dct and \"founded\" in dct:\n        return Publisher(dct&#91;\"name\"], dct&#91;\"founded\"])\n    if \"title\" in dct and \"author\" in dct and \"published_year\" in dct and \"genres\" in dct and \"publisher\" in dct:\n        publisher = decode_complex(dct&#91;\"publisher\"])\n        return Book(dct&#91;\"title\"], dct&#91;\"author\"], dct&#91;\"published_year\"], dct&#91;\"genres\"], publisher)\n    return dct\n\njson_string = '''\n{\n    \"title\": \"To Kill a Mockingbird\",\n    \"author\": \"Harper Lee\",\n    \"published_year\": 1960,\n    \"genres\": &#91;\"Fiction\", \"Drama\"],\n    \"publisher\": {\n        \"name\": \"J.B. Lippincott &amp; Co.\",\n        \"founded\": 1836\n    }\n}\n'''\nbook = json.loads(json_string, object_hook=decode_complex)\nprint(book.title)             # Output: To Kill a Mockingbird\nprint(book.publisher.name)    # Output: J.B. Lippincott &amp; Co.\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"7-loading-vs-dumping-\"><strong>Loading vs dumping<\/strong><\/h2>\n\n\n\n<p>The Python json module includes four functions: dump(), dumps() load() and loads(). It can get tricky to distinguish between them. One helpful trick is to associate the letter &#8216;S&#8217; with &#8220;String.&#8221; Hence you can link loads() to &#8220;load-s&#8221; (loading from a string). <\/p>\n\n\n\n<p>Dumps() to &#8220;dump-s&#8221; (dumping into a string). This clarification makes it easier to understand that load() and dump() work with file objects whereas loads() and dumps() deal with string operations.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"8-conclusion-\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Working with JSON data in Python is crucial for a range of tasks particularly when interacting with APIs and web services. Understanding how to utilize functions like json.load, json.loads, json.dump and json.dumps well as creating custom encoders and decoders allows you to effectively manage and modify JSON data. <\/p>\n\n\n\n<p>This guide serves as a starting point, for navigating JSON in Python enabling you to confidently tackle tasks related to data serialization and deserialization.<\/p>\n\n\n\n<p>Discover how&nbsp;<a href=\"https:\/\/www.ipway.com\/\">IPWAY\u2019s<\/a>&nbsp;innovative solutions can revolutionize your parsing experience for a better and more efficient approach.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>JSON (JavaScript Object Notation) has become a player in the field of data exchange because of its straightforwardness and ease of understanding. Python, an used programming language offers strong capabilities for managing JSON data. This piece explores the details of processing JSON data in Python with a focus on the json.load function and other related&hellip; <a class=\"more-link\" href=\"https:\/\/www.ipway.com\/blog\/json-load-in-python\/\">Continue reading <span class=\"screen-reader-text\">Parsing Json.load data in Python<\/span><\/a><\/p>\n","protected":false},"author":6,"featured_media":1092,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ub_ctt_via":"","footnotes":""},"categories":[25],"tags":[],"class_list":["post-1082","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-what-is","entry"],"featured_image_src":"https:\/\/www.ipway.com\/blog\/wp-content\/uploads\/2024\/05\/Parsing-json.load-in-python.jpg","author_info":{"display_name":"Roxana Anghel","author_link":"https:\/\/www.ipway.com\/blog\/author\/roxana-editor\/"},"_links":{"self":[{"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/posts\/1082","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/comments?post=1082"}],"version-history":[{"count":13,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/posts\/1082\/revisions"}],"predecessor-version":[{"id":1097,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/posts\/1082\/revisions\/1097"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/media\/1092"}],"wp:attachment":[{"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/media?parent=1082"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/categories?post=1082"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ipway.com\/blog\/wp-json\/wp\/v2\/tags?post=1082"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}