{"id":3330,"date":"2020-02-13T20:00:55","date_gmt":"2020-02-13T20:00:55","guid":{"rendered":"https:\/\/www.askpython.com\/?p=3330"},"modified":"2020-02-13T20:04:35","modified_gmt":"2020-02-13T20:04:35","slug":"python-json-module","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python-modules\/python-json-module","title":{"rendered":"Python json Module"},"content":{"rendered":"\n<p>Before we dive into the Python JSON module, let&#8217;s understand what JSON is. The <strong>JSON<\/strong> (JavaScript Object Notation) is a standardized format that allows exchanging of data across the internet. <\/p>\n\n\n\n<p>Since this has become the standard for any information exchange through the internet, it makes sense for any Python application to send and receive data using this format.<\/p>\n\n\n\n<p>Python&#8217;s built-in <strong>json<\/strong> module is the interface that converts Python objects into JSON objects.<\/p>\n\n\n\n<p>In this tutorial, let&#8217;s take a look at some of the most commonly used methods in the json module.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Format of a JSON object<\/h2>\n\n\n\n<p>Before going into the module details, let&#8217;s understand what a JSON object consists of.<\/p>\n\n\n\n<p>This is actually very similar to a Python dictionary, where you have a set of <strong>{Key: value}<\/strong> pairs. The only small difference is that a JSON object has an opening and closing curly parenthesis.<\/p>\n\n\n\n<p>Given below is a simple example of a <strong>JSON<\/strong> object<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n{\n    &quot;name&quot;: &quot;John&quot;,\n    &quot;age&quot;: 42,\n    &quot;married&quot;: True,\n    &quot;qualifications&quot;: &#x5B;&quot;High School Diploma&quot;, &quot;Bachelors&quot;]\n}\n<\/pre><\/div>\n\n\n<p>The JSON object can consist of various attributes, including strings, integers or even lists.<\/p>\n\n\n\n<p>Now that we know what a JSON object is made of, let&#8217;s look at the Python <strong>json<\/strong> module&#8217;s methods.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Import the Python json module<\/h2>\n\n\n\n<p>Python already has the <strong>json<\/strong> module ready with it, so there is no need to install using pip.<\/p>\n\n\n\n<p>To import this module, simply type<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">json.dumps() &#8211; Construct a JSON object<\/h2>\n\n\n\n<p>We can encode a Python object into a JSON object using the <code>json.dumps()<\/code> method.<\/p>\n\n\n\n<p>You can think of <code>dumps()<\/code> as serializing the Python object into a Python JSON object and returning a string. This is needed if you wish to transfer data across the internet.<\/p>\n\n\n\n<p>The encoded data is mentioned in the below table, for different Python objects.<\/p>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"\"><thead><tr><th>Python<\/th><th>JSON<\/th><\/tr><\/thead><tbody><tr><td><strong>dict<\/strong><\/td><td>object<\/td><\/tr><tr><td><strong>list<\/strong>, <strong>tuple<\/strong><\/td><td>array<\/td><\/tr><tr><td><strong>str<\/strong><\/td><td>string<\/td><\/tr><tr><td><strong>int<\/strong>, <strong>float<\/strong>, <strong>int<\/strong>&#8211; &#038; <strong>float<\/strong>-derived Enums<\/td><td>number<\/td><\/tr><tr><td><strong>True<\/strong><\/td><td>true<\/td><\/tr><tr><td><strong>False<\/strong><\/td><td>false<\/td><\/tr><tr><td><strong>None<\/strong><\/td><td>null<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>This takes any Python object that can be serialized as an argument and returns a string.<\/p>\n\n\n\n<p>Format:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\njson_object = json.dumps(serializable_object)\n<\/pre><\/div>\n\n\n<p>Here, <code>serializable_object<\/code> is a Python object, such as a list, string, etc, that can be serializable. It cannot be a function\/lambda, etc.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\npython_object = &#x5B;&#039;Hello&#039;, &#039;from&#039;, &#039;AskPython&#039;, 42]\n\njson_object = json.dumps(python_object)\n\nprint(type(json_object), json_object)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;class &#039;str&#039;&gt; &#x5B;&quot;Hello&quot;, &quot;from&quot;, &quot;AskPython&quot;, 42]\n<\/pre><\/div>\n\n\n<p>This method will raise a <code>TypeError<\/code> if the object is not serializable.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; import json\n&gt;&gt;&gt; a = lambda x : x * 2\n&gt;&gt;&gt; a(2)\n4\n&gt;&gt;&gt; json.dumps(a)\nTraceback (most recent call last):\n    raise TypeError(f&#039;Object of type {o.__class__.__name__}\nTypeError: Object of type function is not JSON serializable\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Sorting Keys of a Dict<\/h3>\n\n\n\n<p>If we&#8217;re passing a <a href=\"https:\/\/www.askpython.com\/python\/dictionary\/python-dictionary-dict-tutorial\" class=\"rank-math-link\">Python dictionary<\/a> into <code>json.dumps()<\/code>, we can specify another parameter <code>sort_keys<\/code>, which will make the Python json object have sorted keys.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\ndict_obj = {1:&quot;one&quot;, 20: &quot;twenty&quot;, 5:&quot;five&quot;}\n\njson_obj = json.dumps(dict_obj, sort_keys = True)\n\nprint(json_obj)\n<\/pre><\/div>\n\n\n<p>Output<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n{&quot;1&quot;: &quot;one&quot;, &quot;5&quot;: &quot;five&quot;, &quot;20&quot;: &quot;twenty&quot;}\n<\/pre><\/div>\n\n\n<p>Our output indeed has sorted keys. <\/p>\n\n\n\n<p class=\"has-text-color has-background has-text-align-center has-very-light-gray-color has-vivid-cyan-blue-background-color\"><strong>NOTE<\/strong>: the numbers are converted into strings since it is encoded into JSON. It will be properly deserialized back into integers on using appropriate methods.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Pretty Printing Python JSON objects<\/h3>\n\n\n\n<p>We can use the <code>indent<\/code> parameter of <code>json.dumps()<\/code> to specify the indentation level. Usually, <code>indent = 4<\/code> will make the output look really good.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\ndict_obj = {1:&quot;one&quot;, 20: &quot;twenty&quot;, 5:&quot;five&quot;}\n\njson_obj = json.dumps(dict_obj, sort_keys = True, indent = 4)\n\nprint(json_obj)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n{\n    &quot;1&quot;: &quot;one&quot;,\n    &quot;5&quot;: &quot;five&quot;,\n    &quot;20&quot;: &quot;twenty&quot;\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">json.dump() &#8211; Dump into a file<\/h3>\n\n\n\n<p>We can also dump an object into a file, if you wish to use it later, using another method <code>json.dump()<\/code>.<\/p>\n\n\n\n<p><strong>Format<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\njson.dump(data, file_object)\n<\/pre><\/div>\n\n\n<p>The <code>json.dump()<\/code> method takes in data and writes it to a file object.<\/p>\n\n\n\n<p>So you can open a new file and write to that file object using <code>json.dump()<\/code><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\npython_object = &#x5B;&#039;Hello&#039;, &#039;from&#039;, &#039;AskPython&#039;, 42]\n\nwith open(&quot;sample.json&quot;, &quot;w&quot;) as wf:\n    json.dump(python_object, wf)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nuser@AskPython $ cat sample.json\n&#x5B;&quot;Hello&quot;, &quot;from&quot;, &quot;AskPython&quot;, 42]\n<\/pre><\/div>\n\n\n<p>As you can see, the Python object was indeed dumped to the file.<\/p>\n\n\n\n<p>Now, let&#8217;s take that JSON object we showed in the first example and store it into a file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\njson_object = {\n    &quot;name&quot;: &quot;John&quot;,\n    &quot;age&quot;: 42,\n    &quot;married&quot;: True,\n    &quot;qualifications&quot;: &#x5B;&quot;High School Diploma&quot;, &quot;Bachelors&quot;]\n}\n\nwith open(&quot;sample.json&quot;, &quot;w&quot;) as wf:\n    json.dump(json_object, wf)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\nuser@AskPython $ cat sample.json\n{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 42, &quot;married&quot;: true, &quot;qualifications&quot;: &#x5B;&quot;High School Diploma&quot;, &quot;Bachelors&quot;]}\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Deserialize JSON objects<\/h2>\n\n\n\n<p>Similar to encoding a Python object into a JSON object, we can also do the reverse, by converting a JSON object into a Python object. This is called <strong>deserialization<\/strong>.<\/p>\n\n\n\n<p>We can do this using the methods <code>json.loads()<\/code> and <code>json.load()<\/code>, similar to <code>json.dumps()<\/code> and <code>json.dump()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">json.loads()<\/h3>\n\n\n\n<p>This converts a json object encoded using <code>json.dumps()<\/code> back into a Python object.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\npython_object = &#x5B;&#039;Hello&#039;, &#039;from&#039;, &#039;AskPython&#039;, 42]\n\nencoded_object = json.dumps(python_object)\n\ndecoded_object = json.loads(encoded_object)\n\nprint(type(decoded_object), decoded_object)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;class &#039;list&#039;&gt; &#x5B;&#039;Hello&#039;, &#039;from&#039;, &#039;AskPython&#039;, 42]\n<\/pre><\/div>\n\n\n<p>We have successfully obtained our old list object back!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">json.load() &#8211; Deserialize from a file<\/h3>\n\n\n\n<p>This performs the reverse operation of <code>json.dump()<\/code>, by converting the json object back from a file, into a Python object.<\/p>\n\n\n\n<p>Let&#8217;s take our <code>sample.json<\/code> file, and get back the data using this method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\n\nwith open(&quot;sample.json&quot;, &quot;r&quot;) as rf:\n    decoded_data = json.load(rf)\n\nprint(decoded_data)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n{&#039;name&#039;: &#039;John&#039;, &#039;age&#039;: 42, &#039;married&#039;: True, &#039;qualifications&#039;: &#x5B;&#039;High School Diploma&#039;, &#039;Bachelors&#039;]}\n<\/pre><\/div>\n\n\n<p>Indeed, we have again got back our old <em>JSON<\/em> object, that we stored in the file!<\/p>\n\n\n\n<p>Now that we&#8217;ve covered the most commonly used methods of this module, let&#8217;s go to the next step: Creating our own JSON Encoder!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Create our own JSON Encoder<\/h2>\n\n\n\n<p>The <code>json<\/code> module uses an encoder called <code>json.JSONEncoder<\/code>, which uses the rules in the table given above to encode Python objects.<\/p>\n\n\n\n<p>However, it does not encode all Python objects and depending on the problem we face, we may need to write our own JSON Encoder to encode those objects in a special way.<\/p>\n\n\n\n<p>To do that, we must write our custom Encoder Class. Let&#8217;s call it <code>MyEncoder<\/code>. This <a href=\"https:\/\/www.askpython.com\/python\/oops\/inheritance-in-python\" class=\"rank-math-link\">must extend<\/a> the <code>json.JSONEncoder<\/code> class, to add to its existing features.<\/p>\n\n\n\n<p>For this demonstration, we&#8217;ll take numpy arrays and convert them to Python JSON objects. Now the json module by default cannot handle numpy arrays so if you try to convert a numpy array without our extended class, you&#8217;ll get a TypeError:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nTypeError: Object of type ndarray is not JSON serializable\n<\/pre><\/div>\n\n\n<p>Let&#8217;s write this class to serialize and encode a numpy array into json objects as well, by converting it into a Python list, in our <code>default()<\/code> handler method.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport json\nimport numpy as np\n\nclass MyEncoder(json.JSONEncoder):\n    # Handles the default behavior of\n    # the encoder when it parses an object &#039;obj&#039;\n    def default(self, obj):\n        # If the object is a numpy array\n        if isinstance(obj, np.ndarray):\n            # Convert to Python List\n            return obj.tolist()\n        else:\n            # Let the base class Encoder handle the object\n            return json.JSONEncoder.default(self, obj)\n\n\n# Numpy array of floats\na = np.arange(1, 10, 0.5)\nprint(type(a), a)\n\n# Pass our encoder to json.dumps()\nb = json.dumps(a, cls=MyEncoder)\nprint(b)\n\n<\/pre><\/div>\n\n\n<p>We finally encode it, by passing the class name to the <code>cls<\/code> parameter of <code>json.dumps()<\/code>.<\/p>\n\n\n\n<p>So, the encoding call will be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\njson_object = json.dumps(python_object, cls=MyEncoder)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&lt;class &#039;numpy.ndarray&#039;&gt; &#x5B;1.  1.5 2.  2.5 3.  3.5 4.  4.5 5.  5.5 6.  6.5 7.  7.5 8.  8.5 9.  9.5]\n&#x5B;1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]\n<\/pre><\/div>\n\n\n<p>Indeed, our custom encoder can now convert numpy arrays into JSON objects! We have now completed our first complex encoder.<\/p>\n\n\n\n<p>You can extend this functionality to write different encoders for your specific use case!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned how we can use Python&#8217;s <code>json<\/code> module to do various operations involving JSON objects.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a class=\"rank-math-link rank-math-link\" href=\"https:\/\/docs.python.org\/3\/library\/json.html\" target=\"_blank\" rel=\"noopener\">Official Python Documentation<\/a> on the JSON module<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Before we dive into the Python JSON module, let&#8217;s understand what JSON is. The JSON (JavaScript Object Notation) is a standardized format that allows exchanging of data across the internet. Since this has become the standard for any information exchange through the internet, it makes sense for any Python application to send and receive data [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":3352,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-3330","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-modules"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3330","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=3330"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/3330\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/3352"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=3330"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=3330"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=3330"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}