Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Create JSON File

#1
Python Create JSON File

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;852705&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p>This article focuses on working with a JSON file. <a rel="noreferrer noopener" href="https://blog.finxter.com/parse-json-data-in-python/" data-type="post" data-id="197286" target="_blank">JSON</a> is an acronym for JavaScript Object Notation. This is a flat-text file formatted based on JavaScript (JS) Syntax. </p>
<p>This file is most commonly noted for its ability to transmit data to/from web applications, such as sending/receiving data from a Server/Client to display or retrieve said data.</p>
<p>The JSON file structure has keys and values similar to a Python <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary/" target="_blank">Dictionary</a>.</p>
<p>This structure can contain strings, boolean, integers, floats, <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">lists</a>, and much more. This file structure can be as simple or complex as needed.</p>
<p>This article works with Rivers Clothing, a new start-up. They have hired their first three (3) employees. This employee data is displayed as a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">emps = {"hires": [{"ID": 324, "name": "Alex Smith", "title": "Manager"}, {"ID": 325, "name": "Micah Jones", "title": "Designer"}, {"ID": 326, "name": "Sam Quinn", "title": "Coder"}]}</pre>
<hr class="wp-block-separator has-alpha-channel-opacity wp-embed-aspect-16-9 wp-has-aspect-ratio" />
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write code to create and work with a JSON File</em><em>?</em></p>
<ol type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li>Python Create JSON File if Not Exists</li>
<li>Python Create JSON String from <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a></li>
<li>Python Create JSON File and Write Data</li>
<li>Python Read JSON File</li>
<li>Python Access JSON Elements</li>
<li>Python Delete JSON Elements</li>
</ol>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python Create JSON File if Not Exists</h2>
<p class="has-global-color-8-background-color has-background">This example creates an empty JSON file if one does not exist in the current working directory.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4, 6-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os filename = 'employees.json'
isFile = os.path.isfile(filename) if (not isFile): with open(filename, 'w') as fp: pass
else: print(f'The {filename} file exists.')</pre>
<p>The first line in the above code snippet imports Python’s built-in <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="URL" data-id="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os</code></a> library. This allows access to and manipulation of files and folders. </p>
<p>The following line declares the JSON file name, <code>employees.json</code> and saves it to the variable <code>filename</code>.</p>
<p>The next line calls the <a rel="noreferrer noopener" href="https://blog.finxter.com/exploring-pythons-os-module/" data-type="URL" data-id="https://blog.finxter.com/exploring-pythons-os-module/" target="_blank"><code>os.path.isfile()</code></a> function and passes it one (1) argument, <code>filename</code>. This function checks the current directory for the existence of the <code>employees.json</code> file</p>
<p>The first time this code runs, and this file is <strong>not </strong>found (<code>isFile </code>is False), an empty file is created and placed into the current working directory. </p>
<p class="has-global-color-8-background-color has-background"><strong><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />Note</strong>: The <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-pass-statement/" data-type="URL" data-id="https://blog.finxter.com/python-pass-statement/" target="_blank">pass</a></code> statement is a placeholder code and does nothing when executed. This is used here so a file is created, and nothing else occurs.</p>
<p>If this code is rerun or the file exists, the following message is output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td>The <code>employees.json</code> file exists.</td>
</tr>
</tbody>
</table>
</figure>
<p>To create this file in a sub-folder, you would modify the code as follows:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os filename = 'files\\employees.json'
isFile = os.path.isfile(filename) if (not isFile): with open(filename, 'w') as fp: pass
else: print(f'The {filename} file exists.')</pre>
<p>When this code runs, the files folder is checked for the existence of the <code><code>employees</code>.json</code> file.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-create-and-work-with-a-json-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPcrUJjfmOwE%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python Create JSON String from List of Dictionaries</h2>
<p class="has-global-color-8-background-color has-background">This example creates a JSON string from a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1, 13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import json emps = {"hires" :[{"empID": "RC-3243", "name": "Alexa Smith", "title": "Manager"}, {"empID": "RC-3244", "name": "Micah Jones", "title": "Designer"}, {"empID": "RC-3245", "name": "Sam Quinn", "title": "Coder"}]} json_str = json.dumps(emps, indent=4)
print(json_str)</pre>
<p>The above code snippet imports the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/json.html" data-type="URL" data-id="https://docs.python.org/3/library/json.html" target="_blank"><code>json</code></a> library. This library allows access to JSON functions. </p>
<p>The following three (3) lines construct a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a> containing data for the new hires. The results save to <code>emps</code>.</p>
<p>Next, <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/json.html" data-type="URL" data-id="https://docs.python.org/3/library/json.html" target="_blank">json.dumps()</a> </code>is called and passed two (2) arguments: a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a>, <code>emps</code>, and for formatting, spaces to indent. The results save to <code>json_str</code> and output to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>{<br />"hires": [<br /> {<br /> "ID": 3243,<br /> "name": "Alexa Smith",<br /> "title": "Manager"<br /> },<br /> {<br /> "ID": 3244,<br /> "name": "Micah Jones",<br /> "title": "Designer"<br /> },<br /> {<br /> "ID": 3245,<br /> "name": "Sam Quinn",<br /> "title": "Coder"<br /> } <br /> ]<br />}</code></td>
</tr>
</tbody>
</table>
</figure>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Note</strong>: The <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/json.html" target="_blank">json.dumps()</a> </code>function formats the JSON string. To write this to a file, <code><a rel="noreferrer noopener" href="https://docs.python.org/3/library/json.html" target="_blank">json.dump()</a></code> is used.</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python Create JSON File and Write Data</h2>
<p class="has-global-color-8-background-color has-background">This example writes a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a> to a JSON file.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="12-13" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import json filename = 'employees.json'
isFile = os.path.isfile(filename) emps = {"hires" :[{"ID": 3243, "name": "Alexa Smith", "title": "Manager"}, {"ID": 3244, "name": "Micah Jones", "title": "Designer"}, {"ID": 3245, "name": "Sam Quinn", "title": "Coder"}]} if (not isFile): with open(filename, 'w') as fp: json.dump(emps, fp, indent=4)
else: print(f'An error occurred writing to {filename}.') </pre>
<p>The above code snippet adds the two (2) highlighted lines to write the formatted JSON string to the <code>employees.json</code> file. </p>
<p>The contents of this file is as follows:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code>{<br />"hires": [<br /> {<br /> "ID": 3243,<br /> "name": "Alexa Smith",<br /> "title": "Manager"<br /> },<br /> {<br /> "ID": 3244,<br /> "name": "Micah Jones",<br /> "title": "Designer"<br /> },<br /> {<br /> "ID": 3245,<br /> "name": "Sam Quinn",<br /> "title": "Coder"<br /> } <br /> ]<br />}</code></td>
</tr>
</tbody>
</table>
</figure>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2> Python Read JSON File</h2>
<p class="has-global-color-8-background-color has-background">In this example, the JSON file saved earlier is read back in.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5,7-10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l print(json_str)</pre>
<p>This code snippet opens, reads the <code>employees.json</code> file and saves it to <code>json_str</code>. Upon each iteration, any additional newline (<code>\n</code>) characters are removed using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-replace-2/" data-type="URL" data-id="https://blog.finxter.com/python-string-replace-2/" target="_blank">replace()</a> </code>function. </p>
<p>Once all lines have been read, the contents of <code>json_str</code> is output to the terminal and is the same as indicated above.</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-create-and-work-with-a-json-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-UkcLQxzPA4%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python Access JSON Elements</h2>
<p class="has-global-color-8-background-color has-background">This example reads in the previously saved JSON file and accesses the ID element from each hire.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="12-14" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str)
alexa_id = all_emps['hires'][0]['ID']
sam_id = all_emps['hires'][2]['ID']
print(alexa_id, sam_id)</pre>
<p>As outlined earlier in this article, the <code>employees.json</code> file is read in, parsed and saved to <code>json_str</code>.</p>
<p>Then, <code>json_str </code>is loaded using <a rel="noreferrer noopener" href="https://docs.python.org/3/library/json.html" data-type="URL" data-id="https://docs.python.org/3/library/json.html" target="_blank"><code>json_loads()</code></a> and passed one (1) argument, the <code>json_str</code> created above. This gives us access to the elements.</p>
<p>The following lines access the Employee IDs for Alexa and Micah and outputs same to the terminal.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><code> 3243 3245</code></td>
</tr>
</tbody>
</table>
</figure>
<p>To iterate and display the <code>ID</code> and <code>name</code> for each new <code>hire</code>, run the following code:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="14-15" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str) for item in all_emps['hires']: print(item['ID'], item['name'])</pre>
<p>Another option is to use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank">List Comprehension</a> to retrieve the data:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">results = [item['ID'] for item in all_emps['hires']]
print(results)</pre>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/how-to-create-and-work-with-a-json-file-in-python/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Python Delete Elements</h2>
<p class="has-global-color-8-background-color has-background">This example reads in the previously saved JSON file and deletes the new hire, Micah Jones.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="12-13,,15-18" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import os
import json filename = 'employees.json'
json_str = '' with open(filename , 'r') as fp: for l in fp: l.replace('\n', '') json_str += l all_emps = json.loads(json_str)
idx = 0 for item in all_emps['hires']: if idx == 1: del all_emps['hires'][idx] idx += 1
print(all_emps)</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Summary</h2>
<p>We hope you enjoyed this article about converting a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-create-a-list-of-dictionaries-in-python/" target="_blank">List of Dictionaries</a> to JSON and everything in between!</p>
<p>Good Luck &amp; Happy Coding!</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Programmer Humor – Blockchain</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="280" height="394" src="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png" alt="" class="wp-image-457795" srcset="https://blog.finxter.com/wp-content/uploads/2022/07/image-31.png 280w, https://blog.finxter.com/wp-content/uplo...13x300.png 213w" sizes="(max-width: 280px) 100vw, 280px" /><figcaption><em>“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.”</em> <strong>source </strong> – <a href="https://imgs.xkcd.com/comics/blockchain.png" data-type="URL" data-id="https://imgs.xkcd.com/comics/blockchain.png" target="_blank" rel="noreferrer noopener">xkcd</a></figcaption></figure>
</div>
</div>


https://www.sickgaming.net/blog/2022/11/...json-file/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016