{"id":117174,"date":"2020-08-26T08:48:16","date_gmt":"2020-08-26T08:48:16","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=12296"},"modified":"2020-08-26T08:48:16","modified_gmt":"2020-08-26T08:48:16","slug":"pretty-print-json-python-one-liner","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/08\/26\/pretty-print-json-python-one-liner\/","title":{"rendered":"Pretty Print JSON [Python One-Liner]"},"content":{"rendered":"<p><strong>Problem<\/strong>: Given a JSON object. How to pretty print it from the shell\/terminal\/command line using a Python one-liner?<\/p>\n<p><strong>Minimal Example<\/strong>: You have given the following JSON object:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{\"Alice\": \"24\", \"Bob\": \"28\"}<\/pre>\n<p>And you want to get the following print output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{ \"Alice\": \"24\", \"Bob\": \"28\"\n}<\/pre>\n<p>How to accomplish this using a Python one-liner?<\/p>\n<h2>Method 0: Python Program + json.dump<\/h2>\n<p>The default way to accomplish this <strong><em>in a Python script<\/em><\/strong> is to import the <code>json<\/code> library to solve the issue:<\/p>\n<p> <iframe loading=\"lazy\" height=\"400px\" width=\"100%\" src=\"https:\/\/repl.it\/@finxter\/jsonprettyprint?lite=true\" scrolling=\"no\" frameborder=\"no\" allowtransparency=\"true\" allowfullscreen=\"true\" sandbox=\"allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals\"><\/iframe> <\/p>\n<p><em><strong>Exercise<\/strong>: Execute the script. What&#8217;s the output? Now change the number of indentation spaces to 2!<\/em><\/p>\n<p>However, what if you want to run this from your operating system terminal as a one-liner command? Let&#8217;s dive into the four best ways!<\/p>\n<h2>Method 1: Terminal \/ Shell \/ Command Line with Echo + Pipe + json.tool<\/h2>\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-12.png\" alt=\"\" class=\"wp-image-12298\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-12.png 657w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-12-300x42.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/08\/image-12-150x21.png 150w\" sizes=\"(max-width: 657px) 100vw, 657px\" \/><\/figure>\n<p>The echo command prints the JSON to the standard output. This is then piped as standard input to the <code>json.tool<\/code> program that pretty prints the JSON object to the standard output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">echo '{\"Alice\": \"24\", \"Bob\": \"28\"}' | python -m json.tool<\/pre>\n<p>The output is the prettier:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{ \"Alice\": \"24\", \"Bob\": \"28\"\n}<\/pre>\n<p>The pipe operator <code>|<\/code> redirects the output to the standard input of the Python script. <\/p>\n<h2>Method 2: Use a File as Input with json.tool<\/h2>\n<p>An alternative is the simple:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">python -m json.tool file.json<\/pre>\n<p>This method is best if you have stored your JSON object in the <code>file.json<\/code> file. If the file contains the same data, the output is the same, too:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{ \"Alice\": \"24\", \"Bob\": \"28\"\n}<\/pre>\n<h2>Method 3: Use Web Resource with json.tool<\/h2>\n<p>If your JSON file resides on a given URL <code>https:\/\/example.com<\/code>, you&#8217;ll best use the following one-liner:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">curl https:\/\/example.com\/ | python -m json.tool<\/pre>\n<p>Again, assuming the same JSON object residing on the server, the output is the same:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">{ \"Alice\": \"24\", \"Bob\": \"28\"\n}<\/pre>\n<h2>Method 4: Use jq<\/h2>\n<p>This is the simplest way but it assumes that you have the <code>jq<\/code> program installed on your machine. You can download <code>jq<\/code> here and also read about the excellent quick-start resources <a href=\"https:\/\/stedolan.github.io\/jq\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/stedolan.github.io\/jq\/\">here<\/a>.<\/p>\n<p>Let&#8217;s dive into the code you can run in your shell:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">jq &lt;&lt;&lt; '{ \"foo\": \"lorem\", \"bar\": \"ipsum\" }'\n{ \"bar\": \"ipsum\", \"foo\": \"lorem\"\n}<\/pre>\n<p>The <code>&lt;&lt;&lt;<\/code> operator passes the string on the right to the standard input of the command on the left. You can learn more about this special pipe operator in <a href=\"https:\/\/unix.stackexchange.com\/questions\/80362\/what-does-mean\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/unix.stackexchange.com\/questions\/80362\/what-does-mean\">this <\/a>SO thread. <\/p>\n<p>While this method is not a Python script, it still works beautifully when executed from a Linux or MacOS shell or the Windows Powershell \/ command line. <\/p>\n<h2>Python One-Liners Book<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<figure class=\"wp-block-image size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: concise statements of useful functionality packed into a single line of code. You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You&#8217;ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You&#8217;ll also learn how to:<\/p>\n<p><strong>\u2022<\/strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy\/nongreedy operators<br \/><strong>\u2022<\/strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting<\/p>\n<p>By the end of the book, you&#8217;ll know how to write Python at its most refined, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners Now!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a JSON object. How to pretty print it from the shell\/terminal\/command line using a Python one-liner? Minimal Example: You have given the following JSON object: {&#8220;Alice&#8221;: &#8220;24&#8221;, &#8220;Bob&#8221;: &#8220;28&#8221;} And you want to get the following print output: { &#8220;Alice&#8221;: &#8220;24&#8221;, &#8220;Bob&#8221;: &#8220;28&#8221; } How to accomplish this using a Python one-liner? Method [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-117174","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117174","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=117174"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/117174\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=117174"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=117174"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=117174"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}