<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ json - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ json - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 23 May 2026 22:20:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/json/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is TOON? How Token-Oriented Object Notation Could Change How AI Sees Data ]]>
                </title>
                <description>
                    <![CDATA[ JSON, or JavaScript Object Notation, was popularized by Douglas Crockford in early 2000. Since then, there’s been no looking back. JSON has become the standardized data exchange format between client and server technologies. JSON was built for humans... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-toon-how-token-oriented-object-notation-could-change-how-ai-sees-data/</link>
                <guid isPermaLink="false">6915f8076f343530b3b31c7b</guid>
                
                    <category>
                        <![CDATA[ llm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tapas Adhikary ]]>
                </dc:creator>
                <pubDate>Thu, 13 Nov 2025 15:23:51 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762978794293/e75f145b-a418-458e-8a41-12fe3add0107.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><code>JSON</code>, or JavaScript Object Notation, was popularized by Douglas Crockford in early 2000. Since then, there’s been no looking back. JSON has become the standardized data exchange format between client and server technologies.</p>
<p>JSON was built for humans. It’s readable, accessible, and universal for APIs to consume data or return responses. But in the modern era of AI, a downside of JSON has really come to light: it’s quite verbose.</p>
<p>Every brace, every quote, and every repeated key consumes tokens. If you spend time building apps that talk to large language models (LLMs), you’ll likely know that tokens are the currency of LLM interactions. The more tokens, the more costly your AI solution is going to be.</p>
<p>Now, there is a new kid in town called <code>TOON</code> (Token-Oriented Object Notation). It promises to enable LLMs to talk to structured data more efficiently, intelligently, and cost-effectively.</p>
<p>This article is the result of my curiosity in exploring TOON. I wanted to learn why it’s trending, how it works, and how you can use it today in your JavaScript/TypeScript and Python projects. I hope you find this equally exciting as I do.</p>
<p>You can find all the source code used in this article in <a target="_blank" href="https://github.com/tapascript/toon-and-json">this GitHub Repository</a>.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-toon">What is Toon?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-is-toon-important-now">Why is TOON Important Now?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-json-vs-toon-learn-with-examples">JSON vs TOON - Learn With Examples</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-toon-with-javascript-typescript">How to Use TOON With JavaScript / TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-toon-with-python">How to Use Toon With Python?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-hold-on-json-might-still-be-betterin-many-cases">Hold On, JSON Might Still Be Better(In Many Cases)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-future-of-toon">The Future of TOON</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-before-we-end">Before We End…</a></p>
</li>
</ol>
<h2 id="heading-what-is-toon">What is Toon?</h2>
<p>TOON is a new data serialization format designed with a code objective:</p>
<blockquote>
<p>Reduce the number of tokens when exchanging structured data with language models.</p>
</blockquote>
<p>While JSON uses verbose syntax with braces, quotes, and commas, TOON relies on a token-efficient tabular style, which is much closer to how LLMs naturally understand structured data.</p>
<p>Let’s make a quick comparison between JSON and TOON:</p>
<p>Here is some JSON with a <code>users</code> array that contains information about two users (two objects):</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"users"</span>: [
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">"role"</span>: <span class="hljs-string">"admin"</span> },
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bob"</span>, <span class="hljs-attr">"role"</span>: <span class="hljs-string">"user"</span> }
  ]
}
</code></pre>
<p>If you wanted to represent the same data in TOON, it would look like this:</p>
<pre><code class="lang-json">users[<span class="hljs-number">2</span>]{id,name,role}:
  <span class="hljs-number">1</span>,Alice,admin
  <span class="hljs-number">2</span>,Bob,user
</code></pre>
<p>Did you notice the differences?</p>
<ul>
<li><p>No quotes, braces, or colons in TOON.</p>
</li>
<li><p>The <code>users[2]{id,name,role}:</code> declares an array of two objects with the fields id, name, and role.</p>
</li>
<li><p>The lines below are simply the data rows.</p>
</li>
</ul>
<p>You can see that TOON visibly reduced the token usage by 30-50%, depending on the data shape.</p>
<h2 id="heading-why-is-toon-important-now">Why is TOON Important Now?</h2>
<p>LLMs like GPT, Gemini, and Claude are token-based systems. Each word, symbol, or chunk costs tokens for input and output. So, if you’re preparing an LLM with structured data input/output like this:</p>
<pre><code class="lang-json">{ <span class="hljs-attr">"products"</span>: [ ... <span class="hljs-number">300</span>, <span class="hljs-string">"items"</span> ... ] }
</code></pre>
<p>You might waste thousands of tokens in quotes, braces, colons, and repeated keys. TOON solves that by focusing on a compact yet structured representation.</p>
<p>Some of the key benefits of TOON are:</p>
<ul>
<li><p>30-50% fewer tokens for uniform data sets.</p>
</li>
<li><p>It has less syntactic clutter, which makes it easier for LLMs to reason about.</p>
</li>
<li><p>It can be nested as we do with JSON.</p>
</li>
<li><p>Works well with languages like Python, Go, Rust, and JavaScript.</p>
</li>
</ul>
<p>TOON is a great augmentation to JSON, especially for AI projects, LLMs, and data-heavy prompts. It may not replace JSON entirely, but it’s suitable for use cases where JSON is considered heavyweight for data exchange.</p>
<h2 id="heading-json-vs-toon-learn-with-examples">JSON vs TOON – Learn With Examples</h2>
<p>Now that you have a basic idea of what TOON does and why it’s helpful, let’s look at some of the most used JSON structures and their equivalent representation in TOON.</p>
<h3 id="heading-1-a-simple-object">1. A Simple Object</h3>
<p>Here’s how you’d represent an object with JSON:</p>
<pre><code class="lang-json">{ <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">"city"</span>: <span class="hljs-string">"Bengaluru"</span> }
</code></pre>
<p>And here’s how it works with TOON:</p>
<pre><code class="lang-json">name: Alice
age: <span class="hljs-number">30</span>
city: Bengaluru
</code></pre>
<h3 id="heading-2-array-of-values">2. Array of Values</h3>
<p>With JSON:</p>
<pre><code class="lang-json">{ <span class="hljs-attr">"colors"</span>: [<span class="hljs-string">"red"</span>, <span class="hljs-string">"green"</span>, <span class="hljs-string">"blue"</span>] }
</code></pre>
<p>With TOON:</p>
<pre><code class="lang-json">colors[<span class="hljs-number">3</span>]: red,green,blue
</code></pre>
<h3 id="heading-3-array-of-objects">3. Array of Objects</h3>
<p>With JSON:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"users"</span>: [
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span> },
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bob"</span> }
  ]
}
</code></pre>
<p>With TOON:</p>
<pre><code class="lang-json">users[<span class="hljs-number">2</span>]{id,name}:
  <span class="hljs-number">1</span>,Alice
  <span class="hljs-number">2</span>,Bob
</code></pre>
<p>Here, <code>users[2]{id,name}</code> represents the schema, and the lines following it contain the actual data rows.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762968459600/03584141-37ae-429d-a999-99ffb93acdcc.png" alt="TOON Schema" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-4-nested-objects">4. Nested Objects</h3>
<p>With JSON:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"user"</span>: {
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span>,
    <span class="hljs-attr">"profile"</span>: { <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>, <span class="hljs-attr">"city"</span>: <span class="hljs-string">"Bengaluru"</span> }
  }
}
</code></pre>
<p>With TOON:</p>
<pre><code class="lang-json">user:
  id: <span class="hljs-number">1</span>
  name: Alice
  profile:
    age: <span class="hljs-number">30</span>
    city: Bengaluru
</code></pre>
<p>Indentation represents nesting. It’s almost YAML-like, but it’s still structured.</p>
<h3 id="heading-5-array-of-objects-with-nested-fields">5. Array of Objects With Nested Fields</h3>
<p>With JSON:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"teams"</span>: [
    {
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Team Alpha"</span>,
      <span class="hljs-attr">"members"</span>: [
        { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span> },
        { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bob"</span> }
      ]
    }
  ]
}
</code></pre>
<p>With TOON:</p>
<pre><code class="lang-json">teams[<span class="hljs-number">1</span>]:
  - name: Team Alpha
    members[<span class="hljs-number">2</span>]{id,name}:
      <span class="hljs-number">1</span>,Alice
      <span class="hljs-number">2</span>,Bob
</code></pre>
<p>This is still perfectly understandable, and much smaller than the JSON format.</p>
<p>Now that you know a bit about TOON syntax, let’s see how to use it with different programming languages.</p>
<h2 id="heading-how-to-use-toon-with-javascript-typescript">How to Use TOON With JavaScript / TypeScript</h2>
<p>In most cases, TOON is not meant to be handwritten. Most TOON data will be generated automatically by software, or you’ll need to encode existing data (say, JSON data) into the TOON format.</p>
<p>And there’s good news – <a target="_blank" href="https://github.com/toon-format">TOON</a> already has an official NPM package that you can use in your JavaScript/TypeScript project to convert your JSON data to TOON and vice versa.</p>
<p>Install it using the following command:</p>
<pre><code class="lang-bash">npm install @toon-format/toon <span class="hljs-comment"># Or yarn add, pnpm install, etc</span>
</code></pre>
<p>The easiest way to create TOON code is by converting JSON to TOON. You can use the <code>encode()</code> method from the above-mentioned NPM package:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { encode } <span class="hljs-keyword">from</span> <span class="hljs-string">"@toon-format/toon"</span>;

<span class="hljs-keyword">const</span> data = {
  <span class="hljs-attr">users</span>: [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">"admin"</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">"Bob"</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span> },
  ],
};

<span class="hljs-keyword">const</span> toonString = encode(data);
<span class="hljs-built_in">console</span>.log(toonString);
</code></pre>
<p>Output:</p>
<pre><code class="lang-json">users[<span class="hljs-number">2</span>]{id,name,role}:
  <span class="hljs-number">1</span>,Alice,admin
  <span class="hljs-number">2</span>,Bob,user
</code></pre>
<p>To do the reverse (TOON =&gt; JSON), you need to use the <code>decode()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { decode } <span class="hljs-keyword">from</span> <span class="hljs-string">"@toon-format/toon"</span>;

<span class="hljs-keyword">const</span> toonString = <span class="hljs-string">`
users[2]{id,name,role}:
  1,Alice,admin
  2,Bob,user
`</span>;

<span class="hljs-keyword">const</span> jsonObject = decode(toonString);
<span class="hljs-built_in">console</span>.log(jsonObject);
</code></pre>
<p>Output:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"users"</span>: [
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Alice"</span>, <span class="hljs-attr">"role"</span>: <span class="hljs-string">"admin"</span> },
    { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Bob"</span>, <span class="hljs-attr">"role"</span>: <span class="hljs-string">"user"</span> }
  ]
}
</code></pre>
<p>You can check out <a target="_blank" href="https://codesandbox.io/p/sandbox/javascript-forked-n4zsww">this sandbox</a> and try out a few encoding and decoding examples.</p>
<h2 id="heading-how-to-use-toon-with-python">How to Use Toon With Python</h2>
<p>Using TOON in Python projects is as straightforward as it was with JavaScript/TypeScript. There are Python packages that can encode JSON data to TOON and decode it back to JSON. The <code>python-toon</code> package is the most famous one in recent days.</p>
<p>First, open your terminal and install the <code>python-toon</code> package:</p>
<pre><code class="lang-bash">pip install python-toon
</code></pre>
<p>Note that if you’re in a virtual environment, you’ll need to activate it first:</p>
<pre><code class="lang-bash">python -m venv venv
<span class="hljs-built_in">source</span> venv/bin/activate
pip install python-toon
</code></pre>
<p>That’s it! Now you’re all set to use the methods to encode and decode your data to and from TOON. First, let’s encode JSON data to TOON using Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> toon <span class="hljs-keyword">import</span> encode

<span class="hljs-comment"># A channel object</span>
channel = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"tapaScript"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">2</span>, <span class="hljs-string">"type"</span>: <span class="hljs-string">"education"</span>}
toon_output = encode(channel)
print(toon_output)
</code></pre>
<p>Output:</p>
<pre><code class="lang-json">name: tapaScript
age: <span class="hljs-number">2</span>
type: education
</code></pre>
<p>Similarly, we can decode TOON back to JSON:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> toon <span class="hljs-keyword">import</span> decode

toon_string = <span class="hljs-string">"""
name: tapaScript
age: 2
type: education
"""</span>

python_struct = decode(toon_string)
print(python_struct)
</code></pre>
<p>Output:</p>
<pre><code class="lang-json">{<span class="hljs-attr">"name"</span>: <span class="hljs-string">"tapaScript"</span>, <span class="hljs-attr">"age"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"type"</span>: <span class="hljs-string">"education"</span>}
</code></pre>
<h2 id="heading-hold-on-json-might-still-be-better-in-many-cases">Hold On, JSON Might Still Be Better (In Many Cases)</h2>
<p>Let’s make it clear that TOON is NOT a universal replacement for JSON. In fact, you should still prefer JSON in many cases, such as when:</p>
<ul>
<li><p>Your data is deeply nested.</p>
</li>
<li><p>Your data is irregular (for example, varying object shapes).</p>
</li>
<li><p>Your application needs strict schema validations or type enforcement.</p>
</li>
<li><p>NON-AI use cases where JSON still stands out and does its job perfectly.</p>
</li>
</ul>
<p>A hybrid approach may even work better. Keep JSON for your application’s data exchange format with APIs, but convert to TOON when it comes to sending data to LLMs.</p>
<h2 id="heading-the-future-of-toon">The Future of TOON</h2>
<p>TOON, though in its infancy, is still getting a lot of attention from the developer community. Its early traction is making it unavoidable to talk about.</p>
<p>TOON has already been explored for:</p>
<ul>
<li><p>Less token overhead for structured training data to fine-tune LLMs.</p>
</li>
<li><p>Compact data exchange in Agent frameworks.</p>
</li>
<li><p>Faster data serialization and deserialization between the MCP and AI workflow engines.</p>
</li>
<li><p>With Serverless AI APIs, where cost and speed matter a lot.</p>
</li>
</ul>
<p>Just as JSON has been a standard for the Web’s data exchange, TOON may soon be standardized for AI data interchange. So next time you craft a prompt or pass structured data to an AI model, try it in the TOON format. You may notice the model gets faster and cheaper.</p>
<h2 id="heading-before-we-end">Before We End…</h2>
<p>That’s all! I hope you found this article insightful.</p>
<p>Let’s connect:</p>
<ul>
<li><p>Subscribe to my <a target="_blank" href="https://www.youtube.com/tapasadhikary?sub_confirmation=1">YouTube Channel</a>.</p>
</li>
<li><p>Check out my FREE courses, <a target="_blank" href="https://www.tapascript.io/courses/40-days-javascript">40 Days of JavaScript</a> and <a target="_blank" href="https://www.tapascript.io/courses/react-design-patterns">15 Days of React Design Patterns</a>.</p>
</li>
<li><p>Follow on <a target="_blank" href="https://www.linkedin.com/in/tapasadhikary/">LinkedIn</a> if you don't want to miss the daily dose of up-skilling tips.</p>
</li>
<li><p>Join my <a target="_blank" href="https://discord.gg/zHHXx4vc2H">Discord Server</a>, and let’s learn together.</p>
</li>
</ul>
<p>See you soon with my next article. Until then, please take care of yourself and keep learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Parse JSON in Python – A Complete Guide With Examples ]]>
                </title>
                <description>
                    <![CDATA[ JSON has become the standard format for data exchange on the web. So you'll run into JSON all the time when working with REST APIs, configuration files, database exports, and more. As a developer, you should know how to parse, manipulate, and generat... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-parse-json-in-python-with-examples/</link>
                <guid isPermaLink="false">69028d2168ede4f821f8f0e8</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Wed, 29 Oct 2025 21:54:41 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761774871223/d4b07c0a-d37e-4197-bb47-f1ee6f51dffd.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON has become the standard format for data exchange on the web. So you'll run into JSON all the time when working with REST APIs, configuration files, database exports, and more. As a developer, you should know how to parse, manipulate, and generate JSON efficiently.</p>
<p>Python's <a target="_blank" href="https://docs.python.org/3/library/json.html">built-in json module</a> provides a straightforward interface for working with JSON data. You'll use it to convert JSON strings into Python dictionaries and lists that you can manipulate with familiar syntax, and then convert your Python data structures back into JSON when you need to send data to an API or save it to a file.</p>
<p>Beyond basic parsing, you'll often need to handle nested structures, validate data integrity, manage, and transform data formats. This guide covers practical JSON parsing techniques you can use in your projects right away. Let’s get started!</p>
<p>🔗 <a target="_blank" href="https://github.com/balapriyac/python-basics/tree/main/parsing-json"><strong>You can find the code examples on GitHub</strong></a>.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you should have:</p>
<ul>
<li><p>Python 3.7 or later installed on your system</p>
</li>
<li><p>Basic understanding of Python dictionaries and lists</p>
</li>
<li><p>Familiarity with Python file operations (opening and reading files)</p>
</li>
<li><p>A text editor or IDE for writing Python code</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-understanding-json-structure-and-basic-parsing">Understanding JSON Structure and Basic Parsing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-work-with-nested-json-objects">How to Work with Nested JSON Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-parse-json-arrays">How to Parse JSON Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-read-json-from-files">How to Read JSON from Files</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-json-parsing-errors">How to Handle JSON Parsing Errors</a></p>
</li>
</ol>
<h2 id="heading-understanding-json-structure-and-basic-parsing">Understanding JSON Structure and Basic Parsing</h2>
<p>JSON represents data using a simple syntax with six data types: <strong>objects (key-value pairs), arrays, strings, numbers, Booleans,</strong> and <strong>null</strong>.</p>
<p>When Python parses JSON, these types map directly to Python equivalents:</p>
<ul>
<li><p>JSON objects become dictionaries,</p>
</li>
<li><p>arrays become lists,</p>
</li>
<li><p>strings remain strings,</p>
</li>
<li><p>numbers become <code>int</code> or <code>float</code>,</p>
</li>
<li><p>true and false become <code>True</code> and <code>False</code>, and</p>
</li>
<li><p>null becomes <code>None</code>.</p>
</li>
</ul>
<p>This direct mapping makes working with JSON in Python intuitive once you understand the correspondence.</p>
<p>Before you start, import the <code>json</code> module that’s built into the Python standard library.</p>
<p>The basic operation in JSON parsing is converting a JSON string into a Python data structure you can work with. Here's how to perform this basic conversion:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

json_string = <span class="hljs-string">'{"name": "Sarah Chen", "age": 28, "city": "Portland"}'</span>
person = json.loads(json_string)

print(person[<span class="hljs-string">"name"</span>]) 
print(person[<span class="hljs-string">"age"</span>])   
print(type(person))
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Sarah Chen
28
&lt;class 'dict'&gt;
</code></pre>
<p>Here, the <code>json.loads()</code> function takes a string containing JSON and returns a Python object. The <code>'s'</code> in <code>'loads'</code> stands for 'string', indicating it works with string data. After parsing, you have a regular Python dictionary that you can access with bracket notation using the JSON keys.</p>
<h2 id="heading-how-to-work-with-nested-json-objects">How to Work with Nested JSON Objects</h2>
<p>Real-world JSON data rarely comes in flat structures. APIs typically return deeply nested objects containing multiple levels of data. Understanding how to navigate these structures is essential for extracting the information you need.</p>
<p>Consider this example of parsing a weather API response that contains nested objects for location data and current conditions:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

weather_data = <span class="hljs-string">'''
{
    "location": {
        "city": "Seattle",
        "state": "WA",
        "coordinates": {
            "latitude": 47.6062,
            "longitude": -122.3321
        }
    },
    "current": {
        "temperature_f": 58,
        "conditions": "Partly Cloudy",
        "humidity": 72,
        "wind": {
            "speed_mph": 8,
            "direction": "NW"
        }
    }
}
'''</span>

weather = json.loads(weather_data)
</code></pre>
<p>After parsing the JSON string with <code>json.loads()</code>, you can access nested values by chaining dictionary keys together:</p>
<pre><code class="lang-python">city = weather[<span class="hljs-string">"location"</span>][<span class="hljs-string">"city"</span>]
temp = weather[<span class="hljs-string">"current"</span>][<span class="hljs-string">"temperature_f"</span>]
wind_speed = weather[<span class="hljs-string">"current"</span>][<span class="hljs-string">"wind"</span>][<span class="hljs-string">"speed_mph"</span>]

print(<span class="hljs-string">f"<span class="hljs-subst">{city}</span>: <span class="hljs-subst">{temp}</span>°F, Wind <span class="hljs-subst">{wind_speed}</span> mph"</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Seattle: 58°F, Wind 8 mph
</code></pre>
<p>In this example, each level of nesting requires another set of brackets. The expression <code>weather["location"]["city"]</code> first accesses the <code>"location"</code> object, then retrieves the <code>"city"</code> value from within it. You can drill down as many levels as needed, like <code>weather["current"]["wind"]["speed_mph"]</code> which traverses three levels deep. This chaining syntax mirrors how you would access the data in the original JSON structure.</p>
<h2 id="heading-how-to-parse-json-arrays">How to Parse JSON Arrays</h2>
<p>JSON arrays represent ordered lists of values and appear frequently in API responses when returning collections of items. Python converts JSON arrays into lists, which you can iterate through or access by index.</p>
<p>Here's an example parsing a list of products from an inventory system:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

products_json = <span class="hljs-string">'''
[
    {
        "id": "PROD-001",
        "name": "Wireless Mouse",
        "price": 24.99,
        "in_stock": true
    },
    {
        "id": "PROD-002",
        "name": "Mechanical Keyboard",
        "price": 89.99,
        "in_stock": false
    },
    {
        "id": "PROD-003",
        "name": "USB-C Hub",
        "price": 34.99,
        "in_stock": true
    }
]
'''</span>

products = json.loads(products_json)
</code></pre>
<p>The JSON string starts with a square bracket, indicating an array at the root level. After parsing, products is a Python list containing three dictionaries.</p>
<p>You can now use standard Python list operations on the parsed data. The <code>len()</code> function returns the number of items, and you can iterate through the list with a for loop. Each iteration gives you a dictionary representing one product, which you access using dictionary syntax.</p>
<pre><code class="lang-python">print(<span class="hljs-string">f"Total products: <span class="hljs-subst">{len(products)}</span>"</span>)

<span class="hljs-keyword">for</span> product <span class="hljs-keyword">in</span> products:
    status = <span class="hljs-string">"Available"</span> <span class="hljs-keyword">if</span> product[<span class="hljs-string">"in_stock"</span>] <span class="hljs-keyword">else</span> <span class="hljs-string">"Out of stock"</span>
    print(<span class="hljs-string">f"<span class="hljs-subst">{product[<span class="hljs-string">'name'</span>]}</span>: $<span class="hljs-subst">{product[<span class="hljs-string">'price'</span>]}</span> - <span class="hljs-subst">{status}</span>"</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Total products: 3
Wireless Mouse: $24.99 - Available
Mechanical Keyboard: $89.99 - Out of stock
USB-C Hub: $34.99 - Available
</code></pre>
<p>You can also access specific array elements by index and filter the data. List indexing works exactly as it does with any Python list, starting at zero.</p>
<pre><code class="lang-python">first_product = products[<span class="hljs-number">0</span>]
print(<span class="hljs-string">f"First product ID: <span class="hljs-subst">{first_product[<span class="hljs-string">'id'</span>]}</span>"</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">First product ID: PROD-001
</code></pre>
<p>You can also use list comprehensions to filter the parsed data, creating a new list containing only products where the "in_stock" value is <code>True</code>.</p>
<pre><code class="lang-python">available_products = [p <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> products <span class="hljs-keyword">if</span> p[<span class="hljs-string">"in_stock"</span>]]
print(<span class="hljs-string">f"Available: <span class="hljs-subst">{len(available_products)}</span> products"</span>)
</code></pre>
<p>Output:</p>
<pre><code class="lang-plaintext">Available: 2 products
</code></pre>
<h2 id="heading-how-to-read-json-from-files">How to Read JSON from Files</h2>
<p>Most applications read JSON from files rather than hardcoded strings. Configuration files, data exports, and cached API responses typically live in JSON files that your application needs to load at runtime.</p>
<p>The <code>json</code> module comes with the <code>load</code> function for reading files that handles opening and parsing in one step.</p>
<p>This code creates a sample configuration file to demonstrate file reading:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># First, let's create a sample config </span>
config_data = {
    <span class="hljs-string">"api_url"</span>: <span class="hljs-string">"https://api.example.com/v2"</span>,
    <span class="hljs-string">"timeout"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-string">"retry_attempts"</span>: <span class="hljs-number">3</span>,
    <span class="hljs-string">"enable_logging"</span>: <span class="hljs-literal">True</span>
}

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'config.json'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> f:
    json.dump(config_data, f, indent=<span class="hljs-number">2</span>)
</code></pre>
<p>The <code>json.dump()</code> function writes Python data to a file, and the <code>indent=2</code> parameter formats the JSON with 2-space indentation to make it human-readable. The <code>'w'</code> mode opens the file for writing, creating it if it doesn't exist or overwriting it if it does.</p>
<p>Now you can read that file back into your application. The <code>json.load()</code> function (without the <code>'s'</code>) reads from a file object and parses the JSON in one operation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> open(<span class="hljs-string">'config.json'</span>, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
    config = json.load(f)

print(<span class="hljs-string">f"API URL: <span class="hljs-subst">{config[<span class="hljs-string">'api_url'</span>]}</span>"</span>)
print(<span class="hljs-string">f"Timeout: <span class="hljs-subst">{config[<span class="hljs-string">'timeout'</span>]}</span> seconds"</span>)
print(<span class="hljs-string">f"Logging: <span class="hljs-subst">{<span class="hljs-string">'Enabled'</span> <span class="hljs-keyword">if</span> config[<span class="hljs-string">'enable_logging'</span>] <span class="hljs-keyword">else</span> <span class="hljs-string">'Disabled'</span>}</span>"</span>)
</code></pre>
<p><strong>Note the difference</strong>: <code>json.loads()</code> parses strings, while <code>json.load()</code> reads from files.</p>
<p>The <code>with</code> statement ensures that the file closes properly even if an error occurs during reading. After the <code>with</code> block completes, you have a Python dictionary containing all the parsed configuration data.</p>
<pre><code class="lang-plaintext">API URL: https://api.example.com/v2
Timeout: 30 seconds
Logging: Enabled
</code></pre>
<h2 id="heading-how-to-handle-json-parsing-errors">How to Handle JSON Parsing Errors</h2>
<p>JSON parsing can fail for many reasons: malformed syntax, unexpected data types, corrupted files, or network issues when fetching from APIs. Your code must handle these errors gracefully rather than crashing.</p>
<p>The <code>json</code> module raises a <code>JSONDecodeError</code> when it runs into invalid JSON. Here's how to catch and handle these errors appropriately.</p>
<p>The <code>try-except</code> block catches any JSON parsing errors:</p>
<ul>
<li><p>The <code>JSONDecodeError</code> exception provides detailed information about what went wrong: <code>e.msg</code> describes the error, <code>e.lineno</code> indicates which line contains the problem, and <code>e.colno</code> shows the character position. This information helps you debug malformed JSON quickly.</p>
</li>
<li><p>The function returns <code>None</code> when parsing fails, allowing calling code to check for this and handle the error appropriately.</p>
</li>
</ul>
<p>Let's test this with a few JSON examples:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Missing closing quote</span>
bad_json1 = <span class="hljs-string">'{"name": "Sarah, "age": 28}'</span>
result1 = parse_json_safely(bad_json1)
print(<span class="hljs-string">f"Result 1: <span class="hljs-subst">{result1}</span>\n"</span>)

<span class="hljs-comment"># Missing closing brace</span>
bad_json2 = <span class="hljs-string">'{"name": "Sarah", "age": 28'</span>
result2 = parse_json_safely(bad_json2)
print(<span class="hljs-string">f"Result 2: <span class="hljs-subst">{result2}</span>\n"</span>)

<span class="hljs-comment"># Extra comma</span>
bad_json3 = <span class="hljs-string">'{"name": "Sarah", "age": 28,}'</span>
result3 = parse_json_safely(bad_json3)
print(<span class="hljs-string">f"Result 3: <span class="hljs-subst">{result3}</span>\n"</span>)

<span class="hljs-comment"># Valid JSON for comparison</span>
good_json = <span class="hljs-string">'{"name": "Sarah", "age": 28}'</span>
result4 = parse_json_safely(good_json)
print(<span class="hljs-string">f"Result 4: <span class="hljs-subst">{result4}</span>"</span>)
</code></pre>
<p>Each malformed JSON string triggers a different error message indicating the specific syntax problem. The error messages help pinpoint exactly where the JSON is invalid. The final example shows that valid JSON parses successfully and returns a dictionary instead of <code>None</code>.</p>
<pre><code class="lang-plaintext">JSON parsing failed: Expecting ',' delimiter
Error at line 1, column 19
Result 1: None

JSON parsing failed: Expecting ',' delimiter
Error at line 1, column 28
Result 2: None

JSON parsing failed: Expecting property name enclosed in double quotes
Error at line 1, column 29
Result 3: None

Result 4: {'name': 'Sarah', 'age': 28}
</code></pre>
<p>When reading JSON files, you should also handle file-related errors. The following function <code>load_json_file_safely</code> handles three types of errors:</p>
<ul>
<li><p><code>FileNotFoundError</code> when the file doesn't exist,</p>
</li>
<li><p><code>PermissionError</code> when the application can't read the file, and</p>
</li>
<li><p><code>JSONDecodeError</code> when the file contains invalid JSON. Each error type gets its own except block with an appropriate message.</p>
</li>
</ul>
<p>The calling code checks if the result is <code>None</code> and falls back to default values, ensuring the application continues running even when the file can't be loaded.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">load_json_file_safely</span>(<span class="hljs-params">filepath</span>):</span>
    <span class="hljs-keyword">try</span>:
        <span class="hljs-keyword">with</span> open(filepath, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
            <span class="hljs-keyword">return</span> json.load(f)
    <span class="hljs-keyword">except</span> FileNotFoundError:
        print(<span class="hljs-string">f"Error: File '<span class="hljs-subst">{filepath}</span>' not found"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
    <span class="hljs-keyword">except</span> PermissionError:
        print(<span class="hljs-string">f"Error: Permission denied reading '<span class="hljs-subst">{filepath}</span>'"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
    <span class="hljs-keyword">except</span> json.JSONDecodeError <span class="hljs-keyword">as</span> e:
        print(<span class="hljs-string">f"Error: Invalid JSON in '<span class="hljs-subst">{filepath}</span>'"</span>)
        print(<span class="hljs-string">f"  <span class="hljs-subst">{e.msg}</span> at line <span class="hljs-subst">{e.lineno}</span>"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>

data = load_json_file_safely(<span class="hljs-string">'missing_file.json'</span>)
<span class="hljs-keyword">if</span> data <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
    print(<span class="hljs-string">"Using default configuration"</span>)
    data = {<span class="hljs-string">"timeout"</span>: <span class="hljs-number">30</span>, <span class="hljs-string">"retries"</span>: <span class="hljs-number">3</span>}
</code></pre>
<p>If you run the above code, you’ll get the following output:</p>
<pre><code class="lang-plaintext">Error: File 'missing_file.json' not found
Using default configuration
</code></pre>
<p>And that’s a wrap! Thank you for making it this far if you’ve following along! 🥳</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>json</code> module provides everything you need for working with JSON data in Python. Here’s a summary of what we covered:</p>
<ul>
<li><p>The core functions handle the most common operations: <code>json.loads()</code> parses JSON strings into Python objects, and <code>json.load()</code> reads and parses JSON from files.</p>
</li>
<li><p>JSON parsing automatically converts between JSON and Python data types. This conversion lets you work with parsed JSON using standard Python syntax.</p>
</li>
<li><p>You can navigate nested JSON by chaining dictionary keys and list indices together. Access nested values like <code>data['section']['subsection']['field']</code> by following the structure down through each level.</p>
</li>
<li><p>Always wrap JSON parsing in <code>try-except</code> blocks when working with external data. The <code>JSONDecodeError</code> exception provides specific information about parsing failures including the error location, helping you debug issues quickly. When reading files, also catch <code>FileNotFoundError</code> and <code>PermissionError</code> to handle common file access problems gracefully.</p>
</li>
</ul>
<p>Get comfortable with these fundamentals and you'll be able to handle most JSON parsing tasks you’ll need for your Python projects. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Transform JSON Data to Match Any Schema ]]>
                </title>
                <description>
                    <![CDATA[ Whether you’re transferring data between APIs or just preparing JSON data for import, mismatched schemas can break your workflow.  Learning how to clean and normalize JSON data ensures a smooth, error-free data transfer. This tutorial demonstrates ho... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/transform-json-data-schema/</link>
                <guid isPermaLink="false">686f40595293ca3e659585b7</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pandas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json-schema ]]>
                    </category>
                
                    <category>
                        <![CDATA[ python beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nneoma Uche ]]>
                </dc:creator>
                <pubDate>Thu, 10 Jul 2025 04:23:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752121420492/513db316-cdc7-47ef-8f20-4911cf5d41f9.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Whether you’re transferring data between APIs or just preparing JSON data for import, mismatched schemas can break your workflow.  Learning how to clean and normalize JSON data ensures a smooth, error-free data transfer.</p>
<p>This tutorial demonstrates how to clean messy JSON and export the results into a new file, based on a predefined schema. The JSON file we’ll be cleaning contains a dataset of 200 synthetic customer records.</p>
<p>In this tutorial, we’ll apply two methods for cleaning the input data:</p>
<ul>
<li><p>With pure Python</p>
</li>
<li><p>With <code>pandas</code></p>
</li>
</ul>
<p>You can apply either of these in your code. But the <code>pandas</code> method is better for large, complex data sets. Let’s jump right into the process.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-add-and-inspect-the-json-file">Add and Inspect the JSON File</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-define-the-target-schema">Define the Target Schema</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-clean-json-data-with-pure-python">How to Clean JSON Data with Pure Python</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-clean-json-data-with-pandas">How to Clean JSON Data with Pandas</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-validate-the-cleaned-json">How to Validate the Cleaned JSON</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-pandas-vs-pure-python-for-data-cleaning">Pandas vs Pure Python for Data Cleaning</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial, you should have a basic understanding of:</p>
<ul>
<li><p>Python dictionaries, lists, and loops</p>
</li>
<li><p>JSON data structure (keys, values, and nesting)</p>
</li>
<li><p>How to read and write JSON files with Python’s <code>json</code> module</p>
</li>
</ul>
<h2 id="heading-add-and-inspect-the-json-file">Add and Inspect the JSON File</h2>
<p>Before you begin writing any code, make sure that the <strong>.json</strong> file you intend to clean is in your project directory. This makes it easy to load in your script using the file name alone.</p>
<p>You can now inspect the data structure by viewing the file locally or loading it in your script, with Python’s built-in <code>json</code> module.</p>
<p>Here’s how (assuming the file name is <strong>“old_customers.json”</strong>):</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1752079424973/3cd77410-6fa9-483d-9a73-edbe4c035327.jpeg" alt="Code to view or print contents of the raw JSON file in terminal" class="image--center mx-auto" width="407" height="231" loading="lazy"></p>
<p>This shows you whether the JSON file is structured as a dictionary or a list. It also prints out the entire file in your terminal. Mine is a dictionary that maps to a list of 200 customer entries. You should always open up the raw JSON file in your IDE to get a closer look at its structure and schema.</p>
<h2 id="heading-define-the-target-schema">Define the Target Schema</h2>
<p>If someone asks for JSON data to be cleaned, it probably means that the <a target="_blank" href="https://json-schema.org/understanding-json-schema/about">current schema</a> is unsuitable for its intended purpose. At this point, you want to be clear on what the final JSON export should look like.</p>
<p>JSON schema is essentially a blueprint that describes:</p>
<ul>
<li><p>required fields</p>
</li>
<li><p>field names</p>
</li>
<li><p>data type for each field</p>
</li>
<li><p>standardized formats (for example, lowercase emails, trimmed whitespace, etc.)</p>
</li>
</ul>
<p>Here’s what the old schema versus the target schema looks like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751956173106/d5957404-57ae-4de9-b61b-90eefa0b9260.jpeg" alt="A screenshot of the old JSON Schema to be transformed" class="image--center mx-auto" width="597" height="222" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751956365336/dcf6a024-1ae6-4c95-92ae-5544ba4cbb3e.jpeg" alt="The expected JSON Schema" class="image--center mx-auto" width="460" height="186" loading="lazy"></p>
<p>As you can see, the goal is to delete the <code>”customer_id”</code> and <code>”address”</code> fields in each entry and rename the rest from:</p>
<ul>
<li><p><code>”name”</code> to <code>”full_name”</code></p>
</li>
<li><p><code>”email”</code> to <code>”email_address”</code></p>
</li>
<li><p><code>”phone”</code> to <code>”mobile”</code></p>
</li>
<li><p><code>”membership_level”</code> to <code>”tier”</code></p>
</li>
</ul>
<p>The output should contain 4 response fields instead of 6, all renamed to fit the project requirements.</p>
<h2 id="heading-how-to-clean-json-data-with-pure-python">How to Clean JSON Data with Pure Python</h2>
<p>Let’s explore using Python’s built-in <code>json</code> module to align the raw data with the predefined schema.</p>
<h3 id="heading-step-1-import-json-and-time-modules">Step 1: Import <code>json</code> and <code>time</code> modules</h3>
<p>Importing <code>json</code> is necessary because we’re working with JSON files. But we’ll use the <code>time</code> module to track how long the data cleaning process takes.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> time
</code></pre>
<h3 id="heading-step-2-load-the-file-with-jsonload">Step 2: Load the file with <code>json.load()</code></h3>
<pre><code class="lang-python">start_time = time.time()
<span class="hljs-keyword">with</span> open(<span class="hljs-string">'old_customers.json'</span>) <span class="hljs-keyword">as</span> file:
    crm_data = json.load(file)
</code></pre>
<h3 id="heading-step-3-write-a-function-to-loop-through-and-clean-each-customer-entry-in-the-dictionary">Step 3: Write a function to loop through and clean each customer entry in the dictionary</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">clean_data</span>(<span class="hljs-params">records</span>):</span>
    transformed_records = []
    <span class="hljs-keyword">for</span> customer <span class="hljs-keyword">in</span> records[<span class="hljs-string">"customers"</span>]:
        transformed_records.append({
                <span class="hljs-string">"full_name"</span>: customer[<span class="hljs-string">"name"</span>],
                <span class="hljs-string">"email_address"</span>: customer[<span class="hljs-string">"email"</span>],
                <span class="hljs-string">"mobile"</span>: customer[<span class="hljs-string">"phone"</span>],
                <span class="hljs-string">"tier"</span>: customer[<span class="hljs-string">"membership_level"</span>],

                })
    <span class="hljs-keyword">return</span> {<span class="hljs-string">"customers"</span>: transformed_records}

new_data = clean_data(crm_data)
</code></pre>
<p><code>clean_data()</code> takes in the original data (<strong>temporarily</strong>) stored in the records variable, transforming it to match our target schema.</p>
<p>Since the JSON file we loaded is a dictionary containing a <code>”customers”</code> key, which maps to a list of customer entries, we access this key and loop through each entry in the list.</p>
<p>In the for loop, we rename the relevant fields and store the cleaned entries in a new list called <code>”transformed_records”</code>.</p>
<p>Then, we return the dictionary, with the <code>”customers”</code> key intact.</p>
<h3 id="heading-step-4-save-the-output-in-a-json-file">Step 4: Save the output in a .json file</h3>
<p>Decide on a name for your cleaned JSON data and assign that to an <code>output_file</code> variable, like so:</p>
<pre><code class="lang-python">output_file = <span class="hljs-string">"transformed_data.json"</span>
<span class="hljs-keyword">with</span> open(output_file, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
    json.dump(new_data, f, indent=<span class="hljs-number">4</span>)
</code></pre>
<p>You can also add a <code>print()</code> statement below this block to confirm that the file has been saved in your project directory.</p>
<h3 id="heading-step-5-time-the-data-cleaning-process">Step 5: Time the data cleaning process</h3>
<p>At the beginning of this process, we imported the time module to measure how long it takes to clean up JSON data using pure Python. To track the runtime, we stored the current time in a <code>start_time</code> variable before the cleaning function, and we’ll now include an <code>end_time</code> variable at the end of the script.</p>
<p>The difference between the <code>end_time</code> and <code>start_time</code> values gives you the total runtime in seconds.</p>
<pre><code class="lang-python">end_time = time.time()
elapsed_time = end_time - start_time

print(<span class="hljs-string">f"Transformed data saved to <span class="hljs-subst">{output_file}</span>"</span>)
print(<span class="hljs-string">f"Processing data took <span class="hljs-subst">{elapsed_time:<span class="hljs-number">.2</span>f}</span> seconds"</span>)
</code></pre>
<p>Here’s how long the data cleaning process took with the pure Python approach:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751957367537/4a33fc16-7158-427e-b715-bec10a586857.jpeg" alt="Script runtime displayed in terminal" class="image--center mx-auto" width="766" height="88" loading="lazy"></p>
<h2 id="heading-how-to-clean-json-data-with-pandas">How to Clean JSON Data with Pandas</h2>
<p>Now we’re going to try achieving the same results as above, using Python and a third-party library called <code>pandas</code>. Pandas is an open-source library used for data manipulation and analysis in Python.</p>
<p>To get started, you need to have the Pandas library installed in your directory. In your terminal, run:</p>
<pre><code class="lang-python">pip install pandas
</code></pre>
<p>Then follow these steps:</p>
<h3 id="heading-step-1-import-the-relevant-libraries">Step 1: Import the relevant libraries</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
</code></pre>
<h3 id="heading-step-2-load-file-and-extract-customer-entries">Step 2: Load file and extract customer entries</h3>
<p>Unlike the pure Python method, where we simply indexed the key name <code>”customers”</code> to access the list of customer data, working with <code>pandas</code> requires a slightly different approach.</p>
<p>We must extract the list before loading it into a DataFrame because <code>pandas</code> expects structured data. Extracting the list of customer dictionaries upfront ensures that we isolate and clean the relevant records alone, preventing errors caused by nested or unrelated JSON data.</p>
<pre><code class="lang-python">start_time = time.time()
<span class="hljs-keyword">with</span> open(<span class="hljs-string">'old_customers.json'</span>, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
    crm_data = json.load(f)

<span class="hljs-comment">#Extract the list of customer entries</span>
clients = crm_data.get(<span class="hljs-string">"customers"</span>, [])
</code></pre>
<h3 id="heading-step-3-load-customer-entries-into-a-dataframe">Step 3: Load customer entries into a DataFrame</h3>
<p>Once you’ve got a clean list of customer dictionaries, load the list into a DataFrame and assign said list to a variable, like so:</p>
<pre><code class="lang-python"><span class="hljs-comment">#Load into a dataframe</span>
df = pd.DataFrame(clients)
</code></pre>
<p>This creates a tabular or spreadsheet-like structure, where each row represents a customer. Loading the list into a DataFrame also allows you to access <code>pandas</code>’ powerful data cleaning methods like:</p>
<ul>
<li><p><code>drop_duplicate()</code>: removes duplicate rows or entries from a DataFrame</p>
</li>
<li><p><code>dropna()</code>: drops rows with any missing or null data</p>
</li>
<li><p><code>fillna(value)</code>: replaces all missing or null data with a specified value</p>
</li>
<li><p><code>drop(columns)</code>: drops unused columns explicitly</p>
</li>
</ul>
<h3 id="heading-step-4-write-a-custom-function-to-rename-relevant-fields">Step 4: Write a custom function to rename relevant fields</h3>
<p>At this point, we need a function that takes in a single customer entry – a row – and returns a cleaned version that fits the target schema (<code>“full_name”</code>, <code>“email_address”</code>, <code>“mobile”</code> and <code>“tier”</code>).</p>
<p>The function should also handle missing data by setting default values like <strong>”Unknown”</strong> or <strong>”N/A”</strong> when a field is absent.</p>
<p><strong>P.S:</strong> At first, I used <code>drop(columns)</code> to explicitly remove the <code>“address”</code> and <code>“customer_id”</code> fields. But it’s not needed in this case, as the <code>transform_fields()</code> function only selects and renames the required fields. Any extra columns are automatically excluded from the cleaned data.</p>
<h3 id="heading-step-5-apply-schema-transformation-to-all-rows">Step 5: Apply schema transformation to all rows</h3>
<p>We’ll use <code>pandas</code>' <code>apply()</code> method to apply our custom function to each row in the DataFrame. This will creates a Series (for example, 0 → {...}, 1 → {...}, 2 → {...}), which is not JSON-friendly.</p>
<p>As <code>json.dump()</code> expects a list, not a Pandas Series, we’ll apply <code>tolist()</code>, converting the Series to a list of dictionaries.</p>
<pre><code class="lang-python"><span class="hljs-comment">#Apply schema transformation to all rows</span>
transformed_df = df.apply(transform_fields, axis=<span class="hljs-number">1</span>)

<span class="hljs-comment">#Convert series to list of dicts</span>
transformed_data = transformed_df.tolist()
</code></pre>
<p>Another way to approach this is with list comprehension. Instead of using <code>apply()</code> at all, you can write:</p>
<pre><code class="lang-python">transformed_data = [transform_fields(row) <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> df.to_dict(orient=<span class="hljs-string">"records"</span>)]
</code></pre>
<p><code>orient=”records”</code> is an argument for <code>df.to_dict</code> that tells pandas to convert the DataFrame to a list of dictionaries, where each dictionary represents a single customer record (that is, one row).</p>
<p>Then the <strong>for loop</strong> iterates through every customer record on the list, calling the custom function on each row. Finally, the list comprehension (<strong>[...]</strong>) collects the cleaned rows into a new list.</p>
<h3 id="heading-step-6-save-the-output-in-a-json-file">Step 6: Save the output in  a .json file</h3>
<pre><code class="lang-python"><span class="hljs-comment">#Save the cleaned data</span>
output_data = {<span class="hljs-string">"customers"</span>: transformed_data}
output_file = <span class="hljs-string">"applypandas_customer.json"</span>
<span class="hljs-keyword">with</span> open(output_file, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> f:
    json.dump(output_data, f, indent=<span class="hljs-number">4</span>)
</code></pre>
<p>I recommend picking a different file name for your <code>pandas</code> output. You can inspect both files side by side to see if this output matches the result you got from cleaning with pure Python.</p>
<h3 id="heading-step-7-track-runtime">Step 7: Track runtime</h3>
<p>Once again, check for the difference between start time and end time to determine the program’s execution time.</p>
<pre><code class="lang-python">end_time = time.time()
elapsed_time = end_time - start_time

<span class="hljs-comment">#print(f"Transformed data saved to {output_file}")</span>
print(<span class="hljs-string">f"Transformed data saved to <span class="hljs-subst">{output_file}</span>"</span>)
print(<span class="hljs-string">f"Processing data took <span class="hljs-subst">{elapsed_time:<span class="hljs-number">.2</span>f}</span> seconds"</span>)
</code></pre>
<p>When I used <strong>list comprehension</strong> to apply the custom function, my script’s runtime was <strong>0.03 seconds</strong>, but with <code>pandas</code>’ <code>apply()</code> function, the total runtime dropped to <strong>0.01 seconds</strong>.</p>
<h3 id="heading-final-output-preview">Final output preview:</h3>
<p>If you followed this tutorial closely, your JSON output should look like this – whether you used the <code>pandas</code> method or the pure Python approach:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1751961256627/d7b585f7-4585-4354-9fa7-a171adb31f90.jpeg" alt="The expected JSON output after schema transformation" class="image--center mx-auto" width="455" height="310" loading="lazy"></p>
<h2 id="heading-how-to-validate-the-cleaned-json">How to Validate the Cleaned JSON</h2>
<p>Validating your output ensures that the cleaned data follows the expected structure before being used or shared. This step helps to catch formatting errors, missing fields, and wrong data types early.</p>
<p>Below are the steps for validating your cleaned JSON file:</p>
<h3 id="heading-step-1-install-and-import-jsonschema">Step 1: Install and import <code>jsonschema</code></h3>
<p><code>jsonschema</code> is a third-party validation library for Python. It helps you define the expected structure of your JSON data and automatically check if your output matches that structure.</p>
<p>In your terminal, run:</p>
<pre><code class="lang-python">pip install jsonschema
</code></pre>
<p>Import the required libraries:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">from</span> jsonschema <span class="hljs-keyword">import</span> validate, ValidationError
</code></pre>
<p><code>validate()</code> checks whether your JSON data matches the rules defined in your schema. If the data is valid, nothing happens. But if there’s an error – like a missing field or wrong data type – it raises a <code>ValidationError</code>.</p>
<h3 id="heading-step-2-define-a-schema">Step 2: Define a schema</h3>
<p>As you know, JSON schema changes with each file structure. If your JSON data differs from what we’ve been working with so far, learn how to create a schema <a target="_blank" href="https://json-schema.org/learn/getting-started-step-by-step#validate-json-data-against-the-schema">here</a>. Otherwise, the schema below defines the structure we expect for our cleaned JSON:</p>
<pre><code class="lang-python">schema = {
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"object"</span>,
    <span class="hljs-string">"properties"</span>: {
        <span class="hljs-string">"customers"</span>: {
            <span class="hljs-string">"type"</span>: <span class="hljs-string">"array"</span>,
            <span class="hljs-string">"items"</span>: {
                <span class="hljs-string">"type"</span>: <span class="hljs-string">"object"</span>,
                <span class="hljs-string">"properties"</span>: {
                    <span class="hljs-string">"full_name"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>},
                    <span class="hljs-string">"email_address"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>},
                    <span class="hljs-string">"mobile"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>},
                    <span class="hljs-string">"tier"</span>: {<span class="hljs-string">"type"</span>: <span class="hljs-string">"string"</span>}
                },
                <span class="hljs-string">"required"</span>: [<span class="hljs-string">"full_name"</span>, <span class="hljs-string">"email_address"</span>, <span class="hljs-string">"mobile"</span>, <span class="hljs-string">"tier"</span>]
            }
        }
    },
    <span class="hljs-string">"required"</span>: [<span class="hljs-string">"customers"</span>]
}
</code></pre>
<ul>
<li><p>The data is an object that must contain a key: <code>"customers"</code>.</p>
</li>
<li><p><code>"customers"</code> must be an <strong>array</strong> (a list), with each object representing one customer entry.</p>
</li>
<li><p>Each customer entry must have four fields–all strings:</p>
<ul>
<li><p><code>"full_name"</code></p>
</li>
<li><p><code>"email_address"</code></p>
</li>
<li><p><code>"mobile"</code></p>
</li>
<li><p><code>"tier"</code></p>
</li>
</ul>
</li>
<li><p>The <code>"required"</code> fields ensure that none of the relevant fields are missing in any customer record.</p>
</li>
</ul>
<h3 id="heading-step-3-load-the-cleaned-json-file">Step 3: Load the cleaned JSON file</h3>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> open(<span class="hljs-string">"transformed_data.json"</span>) <span class="hljs-keyword">as</span> f:
    data = json.load(f)
</code></pre>
<h3 id="heading-step-4-validate-the-data">Step 4: Validate the data</h3>
<p>For this step, we’ll use a <code>try. . . except</code> block to end the process safely, and display a helpful message if the code raises a <code>ValidationError</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">try</span>:
    validate(instance=data, schema=schema)
    print(<span class="hljs-string">"JSON is valid."</span>)
<span class="hljs-keyword">except</span> ValidationError <span class="hljs-keyword">as</span> e:
    print(<span class="hljs-string">"JSON is invalid:"</span>, e.message)
</code></pre>
<h2 id="heading-pandas-vs-pure-python-for-data-cleaning">Pandas vs Pure Python for Data Cleaning</h2>
<p>From this tutorial, you can probably tell that using pure Python to clean and restructure JSON is the more straightforward approach. It is fast and ideal for handling small datasets or simple transformations.</p>
<p>But as data grows and becomes more complex, you might need advanced data cleaning methods that Python alone does not provide. In such cases, <code>pandas</code> becomes the better choice. It handles large, complex datasets effectively, providing built-in functions for handling missing data and removing duplicates.</p>
<p>You can study the <a target="_blank" href="https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf">Pandas cheatsheet</a> to learn more data manipulation methods.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Fetch API vs. Axios vs. Alova: Which HTTP Client Should You Use in 2025? ]]>
                </title>
                <description>
                    <![CDATA[ Before the days of the Fetch API and Axios, developers used callback-based HTTP requests. They manually managed requests with asynchronous operations and, in the process, wrote deeply nested code. This was known as callback hell. Then, in 2015, a pro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/fetch-api-vs-axios-vs-alova/</link>
                <guid isPermaLink="false">67ed4e54f03ad9ca955f36d0</guid>
                
                    <category>
                        <![CDATA[ Alova ]]>
                    </category>
                
                    <category>
                        <![CDATA[ XHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ javascript framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ blob ]]>
                    </category>
                
                    <category>
                        <![CDATA[ axios ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fetch API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fetching apis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API basics  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abdullah Salaudeen ]]>
                </dc:creator>
                <pubDate>Wed, 02 Apr 2025 14:48:52 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743605319873/9f7583a0-1b01-4714-9fe6-f39bed3954e8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Before the days of the Fetch API and Axios, developers used callback-based HTTP requests. They manually managed requests with asynchronous operations and, in the process, wrote deeply nested code. This was known as callback hell.</p>
<p>Then, in 2015, a promise-based API request, the Fetch API, was built into JavaScript ES6 to ease the process. After that, libraries like Axios and Alova also appeared.</p>
<p>But why would anyone consider using a third-party API when the lightweight inbuilt Fetch API is an effective option? Well, Axios and Alova provide more than just fetching simple JSON responses. While Axios automates the parsing of JSON and provides shorthand methods for requests, Alova caches responses which prevents making new requests that are redundant.</p>
<p>So which should you stick to – Fetch API, Axios, or Alova? </p>
<p>In this guide, we’ll examine each of these tools based on their features, performance, and project suitability. Walk with me…</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fetch-api">The Fetch API</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-the-fetch-api">Key Features of the Fetch API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-the-fetch-api">Limitations of the Fetch API</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-axios">Axios</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-axios">Key Features of Axios</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-axios">Limitations of Axios</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-alova">Alova</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-alova">Key Features of Alova</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-alova">Limitations of Alova</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-feature-by-feature-comparison">Feature-by-Feature Comparison</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-cases-and-best-scenarios">Use Cases and Best Scenarios</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-when-to-use-fetch-api">When to Use Fetch API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-axios">When to Use Axios</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-alova">When to Use Alova</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-community-and-ecosystem">Community and Ecosystem</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-ecosystem-and-integrations">Ecosystem and Integrations</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you start this tutorial, you should have a basic understanding of JavaScript and ES6+ features, such as <a target="_blank" href="https://www.freecodecamp.org/news/javascript-async-await/"><code>async/await</code></a>, <a target="_blank" href="https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/">arrow functions</a>, and <a target="_blank" href="https://salaudeenabdu.hashnode.dev/destructuring-in-javascript">object destructuring</a>. Being familiar with the <code>fetch()</code> API will also be helpful, as we’ll compare it with Axios and Alova.</p>
<p>You should also have a fundamental knowledge of HTTP methods (GET, POST, PUT, DELETE, PATCH) and handling API responses based on status codes to better understand the API examples.</p>
<p>While this tutorial focuses on JavaScript, some examples use React. So you should be familiar with React and understand the basics of components, state, and hooks (like <code>useState</code> and <code>useEffect</code>). Alova also works with frameworks like Vue and Svelte.</p>
<p>Basic experience with package managers (NPM or Yarn) is useful for installing dependencies like Axios and Alova. And understanding Node.js and browser environments will help, as Alova works in both contexts.</p>
<p>Lastly, familiarity with state management and caching concepts will enhance your understanding of Alova’s features, as it integrates state management and caching directly into API requests.</p>
<h2 id="heading-the-fetch-api"><strong>The Fetch API</strong></h2>
<p>Fetch API is a promise-based API request feature in JavaScript that was released to replace the old callback-based XMLHttpRequest (XHP). Unlike the old tool, Fetch API is compatible with modern website features, including <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">service workers</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS">Cross-Origin Resource Sharing (CORS)</a>. </p>
<p>With this tool, calling API data is as simple as making a fetch() request on the API URL, as shown below:  </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</span>)
</code></pre>
<p>The <code>fetch()</code> returns the server’s promise which is fulfilled with a response object. Then, you pass in some optional arguments to configure the response as JSON or text, attach it to a variable, and use the data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> products;

  fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</span>)

    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())

    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {

      products = data

      <span class="hljs-built_in">console</span>.log(products)

    })

    .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching data:"</span>, error))
</code></pre>
<p>In the code above, the <code>fetch()</code> requests API data from the URL. The response <code>res</code> gets parsed as JSON <code>res.json</code>. Then, the resulting data is attached to the <code>products</code> variable and logged on the console.  </p>
<p>Since Node.js v17.5, the Fetch API has been available natively, eliminating the reliance on external packages like <code>node-fetch</code>, <code>got</code>, or <code>cross-fetch</code> for handling HTTP requests. This native support in both browsers and Node.js removes the need for additional dependencies, reducing the overall bundle size of your application. With this built-in functionality, the Fetch API has become the go-to tool for making asynchronous API calls in JavaScript applications.</p>
<h3 id="heading-key-features-of-the-fetch-api">Key Features of the Fetch API</h3>
<h4 id="heading-promises-based-syntax">Promises-based syntax</h4>
<p>As I mentioned earlier, the Fetch API uses a promise-based syntax that sends a promise from the server and executes it with a response object. While the <code>.then</code> chaining can be optimal for simple requests, using several <code>.then</code>s can lead to callback hell and give you a hard time tracking errors. This is why the <code>async/await</code> alternative is a more optimal solution. Check out the code example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

      <span class="hljs-keyword">try</span> {

        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</span>);

        <span class="hljs-keyword">if</span> (!response.ok) {

          <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP error! Status: <span class="hljs-subst">${response.status}</span>`</span>);

        }

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();

        products = data

        <span class="hljs-built_in">console</span>.log(products); <span class="hljs-comment">//</span>

      } <span class="hljs-keyword">catch</span> (error) {

        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching data:"</span>, error);

      }

    };

    fetchData();
</code></pre>
<p>As shown above, the fetch makes a get request. Then, the server returns an error status if the response is not ok (returns an error status like <code>error 404</code>). Then, the response gets parsed as JSON and used. </p>
<p>Keep in mind that all methods passed on the response are asynchronous, including the <code>fetch()</code> and the <code>json()</code> parsing.</p>
<h4 id="heading-supports-the-get-post-put-patch-and-delete-methods">Supports the <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> methods</h4>
<p><code>GET</code>, used to receive responses, is the Fetch API’s default method. So when you’re using it, you don’t have to define it explicitly or attach a body. But for methods that send requests like <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code>, you must specify their method and attach a body. </p>
<p>All these methods send requests to the backend. You can send data to the server with <code>POST</code>,  completely replace an existing resource with new data using <code>PUT</code>, partially update with <code>PATCH</code>, or remove the resource with <code>DELETE</code>.  </p>
<ol>
<li><strong>Here’s how you can define a method:</strong></li>
</ol>
<p>In the code below, I set the POST method to send data to the specified API: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>

          <span class="hljs-comment">//...</span>

        });
</code></pre>
<p>Apart from posting data, you can also clear data on the server using <code>DELETE</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

      <span class="hljs-attr">method</span>: <span class="hljs-string">"DELETE"</span>

      <span class="hljs-comment">//...</span>

    });
</code></pre>
<ol start="2">
<li><strong>Then, define the header:</strong></li>
</ol>
<p>Defining the header lets the server understand the type of content you are sending for proper data handling. As shown here, the header asks the server to store the content as a JSON file and set the authorization token to <code>my-classified-token</code><em>.</em> Keep in mind that the token is the API key that will be used to verify user identity upon use.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

          <span class="hljs-attr">header</span>: {

            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application-json"</span>,

            <span class="hljs-string">"Authorization"</span>: <span class="hljs-string">"Bearer my-classified-token"</span>,

          }

          <span class="hljs-comment">//..</span>

        });
</code></pre>
<p>Here is a full list of parameters that can be passed into the header:</p>
<table><tbody><tr><td><p><strong>Header</strong></p></td><td><p><strong>Purpose</strong></p></td></tr><tr><td><p>"Content-Type": "application/json"</p></td><td><p>Tells the server that the request body is in JSON format.</p></td></tr><tr><td><p>"Authorization": "Bearer token"</p></td><td><p>Provides authentication (API keys, JWT, OAuth tokens).</p></td></tr><tr><td><p>"Accept": "application/json"</p></td><td><p>Specifies that the client expects a JSON response.</p></td></tr><tr><td><p>"Content-Type": "application/x-www-form-urlencoded"</p></td><td><p>Used for sending form data instead of JSON.</p></td></tr><tr><td><p>"Origin": "http://example.com"</p></td><td><p>Indicates where the request is coming from (used in CORS).</p></td></tr></tbody></table>

<ol start="3">
<li><strong>Next, attach the body:</strong></li>
</ol>
<p>After specifying the header, you then attach the body. The body is the data being sent to the backend server. It cannot be used with the GET method which only fetches responses. Besides, the information attached should always be in a valid format that matches the content type specified in the headers. You can add as much value as you require to the body.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

          <span class="hljs-attr">header</span>: {

            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application-json"</span>,

            <span class="hljs-string">"Authorization"</span>: <span class="hljs-string">"Bearer my-classified-token"</span>,

          },

          <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">name</span>: <span class="hljs-string">"Laptop"</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1200</span> })

        });
</code></pre>
<h4 id="heading-streaming-data">Streaming Data</h4>
<p>It is also worth noting that the Fetch API facilitates large data handling via streaming. It receives copious data in chunks instead of loading the whole data and buffering in the process. So it data displays real-time as they arrive. Here is a simple example of streaming:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://www.example.com/large-text-file.txt'</span>);

      <span class="hljs-keyword">const</span> reader = response.body.getReader();

      <span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> TextDecoder();

      <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {

        <span class="hljs-keyword">const</span> { done, value } = <span class="hljs-keyword">await</span> reader.read();

        <span class="hljs-keyword">if</span> (done) <span class="hljs-keyword">break</span>;

        <span class="hljs-keyword">const</span> chunk = decoder.decode(value, { <span class="hljs-attr">stream</span>: <span class="hljs-literal">true</span> });

        <span class="hljs-built_in">console</span>.log(chunk); <span class="hljs-comment">// Process the chunk (e.g., display it in UI)</span>

      }

      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Stream complete'</span>);

    }

    fetchData();
</code></pre>
<h4 id="heading-fetching-documents-with-the-dom-parser">Fetching Documents with the DOM Parser</h4>
<p>Unlike its predecessor, XHP, which can directly return a document, Fetch API can’t achieve the same results without using the DOM Parser. To use it, you have to set the response type to text, then convert to a document using the DOMParser. Here is an example:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"example.xml"</span>)

  .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.text()) <span class="hljs-comment">// Get raw text</span>

  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {

    <span class="hljs-keyword">const</span> parser = <span class="hljs-keyword">new</span> DOMParser();

    <span class="hljs-keyword">const</span> doc = parser.parseFromString(data, <span class="hljs-string">"text/xml"</span>); <span class="hljs-comment">// Convert text to Document</span>

    <span class="hljs-built_in">console</span>.log(doc); <span class="hljs-comment">// Now it's a Document object</span>

  })

  .catch(<span class="hljs-built_in">console</span>.error);
</code></pre>
<h4 id="heading-request-cancellation-with-abortcontroller">Request Cancellation with AbortController</h4>
<p>Previously, the Fetch API couldn’t abort requests. But it is now possible with <code>AbortController</code> and <code>AbortSignal</code>. But the AbortController API is not native either, which means there is extra bundle and set up required. </p>
<h3 id="heading-limitations-of-the-fetch-api"><strong>Limitations of the Fetch API</strong></h3>
<h4 id="heading-response-flexibility-or-no-automatic-json-parsing">Response Flexibility or No automatic JSON parsing</h4>
<p>Depends on how you see it. Having to specify whether you want your response as JSON <code>res.json()</code> or text <code>res.text()</code> or blob <code>res.blob()</code> lets you set which response type you want from the get go. But it can also be a limitation since most API fetches are in JSON. This means that alternatives like Axios, which sets defaults as <code>res.json()</code>, helps write shorter and cleaner code, and is therefore often preferred by developers. </p>
<h4 id="heading-no-built-in-requestresponse-interceptors">No built-in request/response interceptors</h4>
<p>Unlike Axios, Fetch API does not have built-in methods that intercept and modify requests or responses. This limitation means you have to write boilerplate code to create a custom interceptor.</p>
<p>For instance, via interception, you can attach an Authorization token automatically before sending requests or asking all 401 errors to automatically reload when receiving responses. With the Fetch API, you have to wrap the <code>fetch()</code> in a function to do that, which means more lines of code.</p>
<p>Here is some code built to mimic request/ response interception:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> customFetch = <span class="hljs-keyword">async</span> (url, options = {}) =&gt; {

      <span class="hljs-comment">// Request Interception</span>

      <span class="hljs-keyword">const</span> modifiedOptions = {

          ...options,

          <span class="hljs-attr">headers</span>: {

              <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,

              <span class="hljs-attr">Authorization</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)}, <span class="hljs-comment">// Interceptor behavior</span>

              ...options.headers

          }

      };



      <span class="hljs-keyword">try</span> {

          <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, modifiedOptions);



          <span class="hljs-comment">// Response Interception</span>

          <span class="hljs-keyword">if</span> (!response.ok) {

              <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Intercepted Error:"</span>, response.status);

          }



          <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();

      } <span class="hljs-keyword">catch</span> (error) {

          <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Fetch error intercepted:"</span>, error);

          <span class="hljs-keyword">throw</span> error;

      }

  };

  <span class="hljs-comment">// Usage (No need to set headers manually)</span>

  customFetch(<span class="hljs-string">'https://api.example.com/data'</span>)

      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))

      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<h4 id="heading-error-handling-requires-additional-logic">Error handling requires additional logic</h4>
<p>The Fetch API only rejects network errors, not failed HTTP status codes like 404 or 501. This means that when a fetching request fails, it does not return a  <code>404 Not Found</code> or <code>500 Internal Server Error</code> unless you configure that with additional code. But Axios does.  </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/invalid-url'</span>)

  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {

    <span class="hljs-keyword">if</span> (!response.ok) { <span class="hljs-comment">// Manually handle non-2xx responses</span>

      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP Error! Status: <span class="hljs-subst">${response.status}</span>`</span>);

    }

    <span class="hljs-keyword">return</span> response.json();

  })

  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error:'</span>, error.message));
</code></pre>
<h2 id="heading-axios"><strong>Axios</strong></h2>
<p>After XHP was replaced with the Fetch API, <a target="_blank" href="https://axios-http.com/docs/intro">Axios</a> emerged in 2016 to address some issues with the new JavaScript-native fetching tool. Built on top of XHP, Axios quickly gained widespread adoption due to combining many Fetch API promise-based features with some methods on the legacy XMLHttpRequest. In no time, it became a popular choice amongst developers.</p>
<p>Axios stands out because it:</p>
<ul>
<li><p>Automates JSON parsing</p>
</li>
<li><p>Has a built-in method to intercept and modify requests and responses </p>
</li>
<li><p>Automates error handling </p>
</li>
<li><p>Automates timeout handling</p>
</li>
<li><p>Can track upload and download progress</p>
</li>
</ul>
<p>And many more features.</p>
<p>In particular, Axios is widely loved because it reduces boilerplate code. Since most API requests encode data with <code>JSON</code>, Axios sets its default parsing to accordingly, which means you don’t have to define <code>JSON</code> again. And why worry anyway, since developers use far fewer <code>res.text()</code> and <code>res.blob()</code> API responses in comparison.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://api.example.com/data'</span>);

    <span class="hljs-built_in">console</span>.log(response.data); <span class="hljs-comment">// JSON is already parsed</span>

  };
</code></pre>
<p>Now, compare that to a like-for-like fetching with Fetch API:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json(); <span class="hljs-comment">// Extra step</span>

    <span class="hljs-built_in">console</span>.log(data);

  };
</code></pre>
<p>Yeah, there’s an extra line, right? That could mean several lines of code for larger codebases. </p>
<h3 id="heading-key-features-of-axios"><strong>Key Features of Axios</strong></h3>
<h4 id="heading-automatic-json-parsing">Automatic JSON Parsing</h4>
<p>As explained above, you don’t have to call <code>res.json()</code> again while using Axios, since the method is automatically set. But what happens, in rare cases, when you want to fetch a blob or text using Axios? Then, you have to set the response type accordingly. Here’s how you can do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://api.example.com/data'</span>, {
      <span class="hljs-attr">responseType</span>: <span class="hljs-string">'text'</span>, <span class="hljs-comment">// Treats response as plain text</span>
    });

    <span class="hljs-built_in">console</span>.log(response.data); <span class="hljs-comment">// Plain text string</span>
  };
</code></pre>
<h4 id="heading-built-in-interceptors-to-modify-requests-and-responses">Built-in Interceptors to Modify Requests and Responses</h4>
<p>Axios comes with its built-in interceptors to intercept and modify API responses or requests. Interceptors can help set authorization tokens for requests or modify global responses and errors before they render. Use the <code>.interceptors.request.use()</code> for requests and <code>.interceptors.response.use()</code> for responses. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

  <span class="hljs-keyword">const</span> apiClient = axios.create({

      <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://api.example.com"</span>,

      <span class="hljs-attr">headers</span>: {

          <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>

      }

  });



  <span class="hljs-comment">// Request Interceptor: Attach Authorization headers</span>

  apiClient.interceptors.request.use(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span> {

      config.headers.Authorization = Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)};

      <span class="hljs-keyword">return</span> config;

  }, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.reject(error));

  <span class="hljs-comment">// Usage: Axios automatically includes the Authorization header</span>

  apiClient.get(<span class="hljs-string">"/data"</span>)

      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>To achieve that with Fetch API, you will have to write an interceptor wrapper on your API, which needs far more boilerplate code.</p>
<h4 id="heading-request-cancellation-with-canceltoken">Request cancellation with CancelToken</h4>
<p>Although now deprecated, Axios used to have its native request cancellation method known as <code>CancelToken</code>. But now, the <code>AbortController</code> API is regarded as a globally-recognized and reliable method for request abortion.</p>
<h4 id="heading-error-handling">Error Handling</h4>
<p>Axios handles errors better by automatically rejecting all non-2xx status codes like <code>Error 404</code> and <code>501</code>. You do not need to check any <code>response.ok</code> message:</p>
<pre><code class="lang-javascript">axios.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/invalid-url'</span>)

  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error Status:'</span>, error.response?.status); <span class="hljs-comment">// Axios auto-rejects non-2xx responses</span>

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error Message:'</span>, error.message);

  });
</code></pre>
<h4 id="heading-built-in-progress-tracking">Built-in Progress Tracking</h4>
<p>Axios incorporates XHP methods like <code>onDownloadProgress</code> and <code>onUploadProgress</code>. This inbuilt feature facilitates tracking download and uploads progress. Whereas with the Fetch API, you’d need <code>ReadableStream</code> to achieve similar results. </p>
<p>Here is an example showing how you can use <code>onUploadProgress</code>: </p>
<pre><code class="lang-javascript">axios.post(url, data, {

    <span class="hljs-attr">onUploadProgress</span>: <span class="hljs-function"><span class="hljs-params">progressEvent</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(progressEvent.loaded)

  });
</code></pre>
<h4 id="heading-supports-other-methods-too">Supports Other Methods, too</h4>
<p>Just like the Fetch API, Axios’ default Method is <code>GET</code>. But you can use the <code>POST</code>, <code>PUT</code>, <code>PATCH</code> or <code>DELETE</code> methods using <code>axios.request()</code>. Here’s how:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

  axios.request({

      <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

      <span class="hljs-attr">url</span>: <span class="hljs-string">"https://api.example.com/users"</span>,

      <span class="hljs-attr">body</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Abdullah"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }, <span class="hljs-comment">// Request body</span>

      <span class="hljs-attr">headers</span>: {

          <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)},

          <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>

      }

  })

  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios Request Error:"</span>, error));
</code></pre>
<p>Axios also provides a shorthand with methods like <code>axios.get</code>, <code>axios.post</code>, <code>axios.put</code>, <code>axios.patch</code>, and <code>axios.delete</code>, as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// POST Request</span>

axios.post(<span class="hljs-string">"https://api.example.com/users"</span>,

  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Abdullah"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }, <span class="hljs-comment">// Request body</span>

  { <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span> } }

)

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios POST Error:"</span>, error));

<span class="hljs-comment">// PUT Request</span>

axios.put(<span class="hljs-string">"https://api.example.com/users/123"</span>,

  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Updated Name"</span> }, <span class="hljs-comment">// Updated data</span>

  { <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)} } }

)

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios PUT Error:"</span>, error));

<span class="hljs-comment">// DELETE Request</span>

axios.delete(<span class="hljs-string">"https://api.example.com/users/123"</span>, {

  <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)} }

})

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User deleted successfully"</span>))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios DELETE Error:"</span>, error));
</code></pre>
<h3 id="heading-limitations-of-axios"><strong>Limitations of Axios</strong></h3>
<h4 id="heading-slightly-larger-bundle-size">Slightly larger bundle size</h4>
<p>Axios <a target="_blank" href="https://bundlephobia.com/package/axios@1.8.4">adds 35 kb</a> of extra bundle, while FetchAPI adds 0. While Axios clearly offers more features than Fetch in every other metric, you have to make do with the larger bundle size. And in an age where lightweight and fast applications are often preferred, you might not want that load.</p>
<h4 id="heading-dependency-on-third-party-maintenance">Dependency on third-party maintenance</h4>
<p>Depending on a third-party option for something as crucial as API might not be desirable. So a native tool like the Fetch API, built within JavaScript, offers more reliability.</p>
<h2 id="heading-alova"><strong>Alova</strong></h2>
<p><a target="_blank" href="https://github.com/alovajs/alova">Alova</a> is a request management library that combines simple API fetching with other functionalities like state management, hooks, and caching, amongst many others.</p>
<p>While we use <code>react-query</code> and <code>SWR</code> to process Axios-fetched data, Alova saves you those extra installations and coding by providing these methods natively. The all-in-one alternative not only fetches responses and sends requests, but also merges requests, caches responses, and optimizes them for UI frameworks. </p>
<p>Built in 2022, Alova’s adoption is still early but nonetheless seems promising. It is supported on browsers, Node.js, and most frameworks, including Vue, React, Svelte, and vanilla JavaScript. But it has limited usage for Angular.js.</p>
<p><a target="_blank" href="https://bundlephobia.com/package/alova@2.6.1">At just 10kb</a>, it is about 3 times smaller than Axios, making it a more lightweight alternative for building fast applications. </p>
<p>You can also use Alova to either replace react-query to facilitate Axios or be the one-stop-shop for everything API integration-related. </p>
<p>Here is a simple Alova fetch:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> alovaInstance.Get(<span class="hljs-string">'https://jsonplaceholder.typicode.com'</span>).send();

<span class="hljs-built_in">console</span>.log(response); <span class="hljs-comment">// Response data</span>
</code></pre>
<p>When you are fetching Alova on React components, you can use the <code>createAlova()</code> to set parameters and <code>useRequest()</code> to manage state. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-comment">// Initialize Alova</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// GET request with useRequest</span>

<span class="hljs-keyword">const</span> Profile = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> { data, loading, error } = useRequest(<span class="hljs-function">() =&gt;</span> alovaInstance.Get(<span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>));

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error fetching profile<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Username: {data.username}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
<h3 id="heading-key-features-of-alova"><strong>Key Features of Alova</strong></h3>
<h4 id="heading-one-stop-shop">One-Stop Shop</h4>
<p>For some functionalities that come built into Alova, Fetch API or Axios might need additional libraries like <code>react-query</code> or <code>SWR</code> to fulfill. </p>
<h4 id="heading-request-sharing-prevents-redundant-requests">Request Sharing Prevents Redundant Requests</h4>
<p>Alova fuses identical requests. Let’s say several components ask for the same data from the API. The Fetch API and Axios send multiple identical requests to the server which creates traffic. But Alova merges them, sends a single request, and shares its response across all components, which reduces network traffic.</p>
<h4 id="heading-state-management">State Management</h4>
<p>With tools like Fetch API and Axios, you have to manage data, loading, and error states manually. Alova lets you do that on the go within a single line of code. Here is how it looks:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-keyword">const</span> { data, loading, error } = useRequest(alova.Get(<span class="hljs-string">"/posts/1"</span>));

<span class="hljs-comment">//...</span>
</code></pre>
<h4 id="heading-advanced-request-management">Advanced Request Management</h4>
<p>Alova offers several request management functionalities with each tailored to specific use cases. With its request management, you can request preload for data to be used later, cache data to prevent reload, manage form submission, handle pagination, and automate refetching when needed. Check out their docs to <a target="_blank" href="https://alova.js.org/tutorial/client/strategy/">read more</a>. </p>
<h4 id="heading-multi-level-caching">Multi-Level Caching</h4>
<p>You can also use Alova to cache data, especially when the response isn’t constantly changing and does not need refetching. Unlike <code>react-query</code> that simply stores caches in RAM, Alova offers a more flexible framework. </p>
<p>Its three-pronged caching modes include the memory mode, cache occupying mode, and recovery mode. While memory mode stores data in the RAM, recovery mode persistently stores it in a Local Storage and is made available for longer periods and even offline. Meanwhile, the occupying mode prevents duplicate or redundant requests coming in quick succession. </p>
<p>Independent on any component, cached data can be accessed anywhere in the app if the request URL and parameters match. These features lower traffic going to servers, reduce buffering, and help facilitating a swifter and better user experience.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-comment">// Initialize Alova instance</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// Define GET request</span>

<span class="hljs-keyword">const</span> getPosts = alovaInstance.Get(<span class="hljs-string">"/posts"</span>, {

  <span class="hljs-attr">cache</span>: {

    <span class="hljs-attr">mode</span>: <span class="hljs-string">"memory"</span>, <span class="hljs-comment">// Caches in memory</span>

    <span class="hljs-attr">expires</span>: <span class="hljs-number">1000</span> * <span class="hljs-number">60</span> * <span class="hljs-number">5</span>, <span class="hljs-comment">// Expires in 5 minutes</span>

  },

});

<span class="hljs-keyword">const</span> PostList = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> { data, loading, error } = useRequest(getPosts);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error fetching data<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-comment">//...</span>

};
</code></pre>
<p>In the example above, Alova caches the response using the memory mode <code>cache: {mode: "memory"}</code> and sets the cache expiration to 5 minutes <code>expires: 1000 * 60 * 5</code><em>.</em> You can change <code>“memory”</code> to <code>“recovery”</code> if you want a longer storage duration. </p>
<h4 id="heading-usage-flexibility">Usage Flexibility</h4>
<p>You can use Alova with either Axios or the Fetch API. Here is an example where I fetched data using Axios and complemented it with Alova state management.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-comment">// Initialize Alova</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// Manage state with Alova</span>

<span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: posts, setData } = useSnapshot([]);

<span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> () =&gt; {

  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>);

  setData(response.data); <span class="hljs-comment">// Store data in Alova state</span>

};

<span class="hljs-comment">//...</span>
</code></pre>
<h4 id="heading-supports-other-methods">Supports Other Methods</h4>
<p>Alova also makes <code>GET</code> its default option while supporting other methods like <code>POST</code>, <code>PATCH</code>, <code>PUT</code> and <code>DELETE</code>. Here is how to use <code>POST</code> in Alova, for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-keyword">const</span> PostForm = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: createPost } = useRequest(alovaInstance.Post(<span class="hljs-string">"/posts"</span>, { title }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

  createPost().then(<span class="hljs-built_in">console</span>.log)

};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PostForm;
</code></pre>
<p>Of course, it has shorthand methods too:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-keyword">const</span> alova = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: createPost } = useRequest(alova.Post(<span class="hljs-string">"/posts"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"New Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: updatePost } = useRequest(alova.Put(<span class="hljs-string">"/posts/1"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"Updated Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: patchPost } = useRequest(alova.Patch(<span class="hljs-string">"/posts/1"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"Patched Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

createPost().then(<span class="hljs-built_in">console</span>.log);

updatePost().then(<span class="hljs-built_in">console</span>.log);

patchPost().then(<span class="hljs-built_in">console</span>.log);
</code></pre>
<h4 id="heading-bundle-size">Bundle Size</h4>
<p>Alova is three times smaller than Axios, but that does not even tell the full story. With Axios and the Fetch API, you need different libraries to handle caching, request deduplication, and retries. But Alova has everything in-built. So using Axios and Fetch API in real code production will always require more bundles than Axios. And overall, Alova facilitates lighter-weight applications compared to Axios and sometimes the Fetch API as well. </p>
<h3 id="heading-limitations-of-alova"><strong>Limitations of Alova</strong></h3>
<h4 id="heading-adoption-is-still-low">Adoption Is Still Low</h4>
<p>While writing this article, I had a hard time getting enough resources on Alova. And that is because it only debuted in July 2022 which means adoption is still early. So, troubleshooting Alova might be problematic since there are fewer Alova-themed API communities, as well as fewer StackOverflow answers, Youtube Tutorials, or GitHub contributions. </p>
<h4 id="heading-potential-stability-amp-long-term-maintenance-risks">Potential Stability &amp; Long-Term Maintenance Risks</h4>
<p>Newer libraries have a higher risk of abandonment. Axios has been around for years, while Alova is still growing. Besides, it has fewer production use cases and battle-tested applications compared to Axios and Fetch.</p>
<h4 id="heading-learning-curve">Learning Curve</h4>
<p>Alova’s learning curve can take some getting used to because it handles API requests differently from tools like Axios or the Fetch API.</p>
<p>Instead of making requests directly, you work with request instances and manage state within Alova’s system. This requires learning new ways to structure API calls and use features like caching and request merging. While it may feel unfamiliar at first, it can help reduce redundant API calls and improve performance once you understand it.</p>
<h4 id="heading-fewer-third-party-integrations">Fewer Third Party Integrations</h4>
<p>Alova has fewer third-party libraries built specifically for it, requiring more manual work for compatibility with existing tools. </p>
<h2 id="heading-feature-by-feature-comparison"><strong>Feature-by-Feature Comparison</strong></h2>
<table><tbody><tr><td><p><strong>Feature</strong></p></td><td><p><strong>Fetch API</strong></p></td><td><p><strong>Axios</strong></p></td><td><p><strong>Alova</strong></p></td></tr><tr><td><p><strong>Ease of Use</strong></p></td><td><p>Medium (requires manual handling)</p></td><td><p>High (user-friendly syntax)</p></td><td><p>Medium (requires new patterns)</p></td></tr><tr><td><p><strong>Performance</strong></p></td><td><p>High (lightweight, native)</p></td><td><p>Medium (slightly larger size)</p></td><td><p>High (optimized for caching &amp; batch requests)</p></td></tr><tr><td><p><strong>JSON Handling</strong></p></td><td><p>Manual parsing (.json())</p></td><td><p>Automatic</p></td><td><p>Automatic</p></td></tr><tr><td><p><strong>Request Cancellation</strong></p></td><td><p>AbortController (manual)</p></td><td><p>Built-in with CancelToken</p></td><td><p>Built-in</p></td></tr><tr><td><p><strong>Interceptors</strong></p></td><td><p>No</p></td><td><p>Yes</p></td><td><p>Yes</p></td></tr><tr><td><p><strong>Timeout Handling</strong></p></td><td><p>No (manual with AbortController)</p></td><td><p>Yes (built-in)</p></td><td><p>Yes (built-in)</p></td></tr><tr><td><p><strong>Data Caching</strong></p></td><td><p>No</p></td><td><p>No (requires third-party caching)</p></td><td><p>Yes (built-in)</p></td></tr><tr><td><p><strong>Retry Mechanism</strong></p></td><td><p>No</p></td><td><p>Yes</p></td><td><p>Yes</p></td></tr><tr><td><p><strong>Error Handling</strong></p></td><td><p>Requires manual handling</p></td><td><p>Automatic rejection for non-2xx status codes</p></td><td><p>Built-in error recovery</p></td></tr><tr><td><p><strong>Browser Support</strong></p></td><td><p>All modern browsers</p></td><td><p>All modern browsers</p></td><td><p>All modern browsers</p></td></tr><tr><td><p><strong>Node.js Support</strong></p></td><td><p>Yes</p></td><td><p>Yes</p></td><td><p>Limited</p></td></tr></tbody></table>

<h2 id="heading-use-cases-and-best-scenarios"><strong>Use Cases and Best Scenarios</strong></h2>
<p>Choosing the right HTTP client for your project depends on several factors, including project complexity, dependencies, and performance considerations. Let’s explore when it’s best to use the Fetch API, Axios, or Alova.</p>
<h3 id="heading-when-to-use-fetch-api">When to Use Fetch API</h3>
<ol>
<li><h4 id="heading-suitable-for-lightweight-projects-and-simple-requests">Suitable for Lightweight Projects and Simple Requests</h4>
</li>
</ol>
<p>The Fetch API is built into modern browsers and is ideal for handling basic HTTP requests without adding dependencies. If your project requires only simple GET, POST, or DELETE requests with minimal configurations, Fetch API is a great choice.</p>
<ol start="2">
<li><h4 id="heading-when-working-in-environments-where-third-party-libraries-are-restricted">When Working in Environments Where Third-Party Libraries Are Restricted</h4>
</li>
</ol>
<p>Certain enterprise or security-sensitive applications may restrict the use of external libraries. Since the Fetch API is built into the browser, it remains a viable option when third-party packages like Axios or Alova are not allowed.</p>
<ol start="3">
<li><h4 id="heading-when-minimal-dependencies-are-preferred">When Minimal Dependencies Are Preferred</h4>
</li>
</ol>
<p>Since Fetch API is native to JavaScript, it does not require installing extra libraries, making it perfect for projects that need to keep dependencies low. This can be particularly beneficial for small lightweight apps or static websites.</p>
<h3 id="heading-when-to-use-axios">When to Use Axios</h3>
<ol>
<li><h4 id="heading-ideal-for-backend-heavy-applications-or-complex-apis">Ideal for Backend-Heavy Applications or Complex APIs</h4>
</li>
</ol>
<p>For projects that require multiple API calls, error handling, and efficient request management, Axios is a solid choice. It allows concurrent requests, request cancellation, and improved control over HTTP headers.</p>
<ol start="2">
<li><h4 id="heading-when-automatic-json-handling-interceptors-and-robust-error-handling-are-needed">When Automatic JSON Handling, Interceptors, and Robust Error Handling Are Needed</h4>
</li>
</ol>
<p>Axios simplifies working with JSON data by automatically parsing responses. It also provides built-in interceptors for request and response transformations, as well as superior error handling compared to Fetch API.</p>
<ol start="3">
<li><h4 id="heading-useful-when-working-with-nodejs-in-full-stack-applications">Useful When Working with Node.js in Full-Stack Applications</h4>
</li>
</ol>
<p>Axios works both in the browser and in Node.js, making it an excellent choice for full-stack applications where a unified API client is needed across the frontend and backend.</p>
<h3 id="heading-when-to-use-alova">When to Use Alova</h3>
<ol>
<li><h4 id="heading-when-working-with-frontend-heavy-applications-react-vue-svelte">When Working with Frontend-Heavy Applications (React, Vue, Svelte)</h4>
</li>
</ol>
<p>Alova integrates well with frontend frameworks and state management tools, making it a great choice for single-page applications (SPAs) that depend on smooth data fetching, pagination, and updates.</p>
<ol start="2">
<li><h4 id="heading-best-for-projects-requiring-optimized-caching-and-data-synchronization">Best for Projects Requiring Optimized Caching and Data Synchronization</h4>
</li>
</ol>
<p>Alova is designed for performance optimization and better caching strategies. It is suitable for applications that rely on real-time data synchronization and need to minimize redundant network requests.</p>
<ol start="3">
<li><h4 id="heading-when-performance-optimization-and-reduced-network-load-are-priorities">When Performance Optimization and Reduced Network Load Are Priorities</h4>
</li>
</ol>
<p>With its intelligent caching mechanisms, Alova can significantly reduce API call frequency, thereby improving the overall performance of the application. It is especially useful in scenarios where network efficiency is crucial, such as mobile applications or progressive web apps (PWAs).</p>
<h2 id="heading-community-and-ecosystem"><strong>Community and Ecosystem</strong></h2>
<p>The community and ecosystem surrounding an HTTP client can impact ease of use, available learning resources, and integration with other tools. Let's explore how the Fetch API, Axios, and Alova are perceived in 2025.</p>
<h3 id="heading-ecosystem-and-integrations"><strong>Ecosystem and Integrations</strong></h3>
<p>While Fetch API is widely supported, developers often supplement it with additional libraries for improved caching, timeouts, and request queuing. This can lead to increased development effort compared to using an out-of-the-box solution like Axios or Alova.</p>
<p>Meanwhile, Axios benefits from a well-established ecosystem with a variety of plugins and extensions, making it easy to integrate with different backend architectures, authentication systems, and request monitoring tools.</p>
<p>Alova is designed to work seamlessly with modern state management libraries such as React Query and Vue Query. These integrations make it an attractive choice for developers focused on optimizing frontend data fetching strategies.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Choosing between the Fetch API, Axios, and Alova depends on your project’s needs and priorities. The Fetch API is best for lightweight applications that require minimal dependencies, while Axios is a robust choice for full-stack applications and backend-heavy environments. Alova, on the other hand, is an excellent option for optimizing data fetching and caching in frontend-focused applications.</p>
<p>As developers explore new ways to enhance performance and reduce network load, Alova's adoption is expected to grow, particularly in SPAs and PWAs. But Axios remains a reliable and widely adopted solution, while the Fetch API continues to be the fundamental building block for HTTP requests in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Send and Parse JSON Data in Golang – Data Encoding and Decoding Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ When building web applications in Golang, working with JSON data is inevitable. Whether you're sending responses to clients or parsing requests, JSON encoding and decoding are essential skills to master.  In this article, we'll explore the different ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/encoding-and-decoding-data-in-golang/</link>
                <guid isPermaLink="false">66b906a2e4bfcbefb35a6b94</guid>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Destiny Erhabor ]]>
                </dc:creator>
                <pubDate>Mon, 05 Aug 2024 13:00:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/ferenc-almasi-HfFoo4d061A-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When building web applications in Golang, working with JSON data is inevitable. Whether you're sending responses to clients or parsing requests, JSON encoding and decoding are essential skills to master. </p>
<p>In this article, we'll explore the different ways to encode and decode JSON in Golang.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-how-to-send-json-responses-encoding">How to Send JSON Responses (Encoding)</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-marshal-function-for-json-encoding">How to Use the Marshal Function for JSON Encoding</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-newencoder-function">How to Use the NewEncoder Function</a></li>
<li><a class="post-section-overview" href="#heading-how-to-parse-json-requests-decoding">How to Parse JSON Requests (Decoding)</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-unmarshal-function-to-parse-json-requests">How to Use the Unmarshal Function to Parse JSON Requests</a></li>
<li><a class="post-section-overview" href="#how-to-use-newdecoder-function-for-json-decoding">How to Use NewDecoder Function for JSON Decoding</a></li>
<li><a class="post-section-overview" href="#heading-custom-json-marshaling-and-unmarshaling">Custom JSON Marshaling and Unmarshaling</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/4e27d014-692d-4c5d-bad0-0bd1af87cef3/how-to-use-json-marshaler">How to Use JSON Marshaler</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-json-unmarshaler">How to Use JSON Unmarshaler</a></li>
<li><a class="post-section-overview" href="#heading-trade-offs">Trade-offs</a></li>
<li><a class="post-section-overview" href="#heading-use-cases-and-recommendations">Use Cases and Recommendations</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-how-to-send-json-responses-encoding">How to Send JSON Responses (Encoding)</h2>
<p>JSON encoding is the process of converting Go data structures into JSON format.</p>
<p>Encoding refers to the process of converting data from one format to another. In the context of computing and data transmission, encoding typically involves converting data into a standardized format that can be easily stored, transmitted, or processed by different systems or applications.</p>
<p>Think of encoding like packing a suitcase for a trip. You take your clothes (data) and pack them into a suitcase (encoded format) so that they can be easily transported (transmitted) and unpacked (decoded) at your destination.</p>
<p>In the case of JSON encoding, the data is converted into a text-based format that uses human-readable characters to represent the data. This makes it easy for humans to read and understand the data, as well as for different systems to exchange and process the data.</p>
<p>Some common reasons for encoding data include:</p>
<ul>
<li>Data compression: Reducing the size of the data to make it easier to store or transmit.</li>
<li>Data security: Protecting the data from unauthorized access or tampering.</li>
<li>Data compatibility: Converting data into a format that can be read and processed by different systems or applications.</li>
<li>Data transmission: Converting data into a format that can be easily transmitted over a network or other communication channels.</li>
</ul>
<p>In Golang, we can use the <code>encoding/json</code> package to encode JSON data.</p>
<h3 id="heading-how-to-use-the-marshal-function-for-json-encoding">How to Use the Marshal Function for JSON Encoding</h3>
<p>The <code>Marshal</code> function is the most commonly used method for encoding JSON data in Golang. It takes a Go data structure as input and returns a JSON-encoded string.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> ( 
    <span class="hljs-string">"encoding/json"</span>
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"net/http"</span>
 )

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> { 
    Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span> 
    Age <span class="hljs-keyword">int</span> <span class="hljs-string">`json:"age"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> { 
    person := Person{  Name: <span class="hljs-string">"John"</span>,  Age: <span class="hljs-number">30</span>, } 

    <span class="hljs-comment">// Encoding - One step</span>
    jsonStr, err := json.Marshal(person) 

    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {  
        http.Error(w, err.Error(), http.StatusInternalServerError)  
        <span class="hljs-keyword">return</span> 
    } 

    w.Write(jsonStr)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
    http.HandleFunc(<span class="hljs-string">"/"</span>, handler) 
    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
 }
</code></pre>
<h4 id="heading-code-explanation">Code Explanation:</h4>
<h6 id="heading-imports">Imports:</h6>
<ul>
<li><code>encoding/json</code>: Provides functions for encoding and decoding JSON.</li>
<li><code>fmt</code>: For printing output.</li>
</ul>
<h6 id="heading-user-struct">User Struct:</h6>
<ul>
<li>Defines a struct <code>User</code> with fields <code>Name</code> and <code>Age</code>.</li>
<li>Struct tags (for example: <code>json:"name"</code>) specify the JSON key names.</li>
</ul>
<h6 id="heading-main-function">main Function:</h6>
<ul>
<li>Creates a <code>User</code> instance.</li>
<li>Calls <code>json.Marshal</code> to encode the <code>user</code> struct into JSON. This returns a byte slice and an error.</li>
<li>If there's no error, it converts the byte slice to a string and prints it.</li>
</ul>
<h3 id="heading-how-to-use-the-newencoder-function">How to Use the NewEncoder Function</h3>
<p>The <code>NewEncoder</code> function is used to encode JSON data to a writer, such as a file or network connection.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> ( 
    <span class="hljs-string">"encoding/json"</span> 
    <span class="hljs-string">"fmt"</span> 
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> { 
    Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span> 
    Age <span class="hljs-keyword">int</span> <span class="hljs-string">`json:"age"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> { 
    person := Person{  Name: <span class="hljs-string">"John"</span>,  Age: <span class="hljs-number">30</span> } 

    <span class="hljs-comment">// Encoding - 2 step . NewEncoder and Encode</span>
    encoder := json.NewEncoder(w) 

    err := encoder.Encode(person) 

    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {  
        http.Error(w, err.Error(), http.StatusInternalServerError)  

        <span class="hljs-keyword">return</span> 
   }}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
   http.HandleFunc(<span class="hljs-string">"/"</span>, handler) http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<h4 id="heading-code-explanation-1">Code Explanation:</h4>
<h6 id="heading-inside-the-handler">Inside the handler:</h6>
<ul>
<li>The <code>handler</code> function is an HTTP handler that handles incoming HTTP requests.</li>
<li><code>w http.ResponseWriter</code>: Used to write the response.</li>
<li><code>r *http.Request</code>: Represents the incoming request.</li>
<li>A <code>Person</code> instance named <code>person</code> was created and initialized with the values <code>Name: "John"</code> and <code>Age: 30</code>.</li>
<li>A JSON encoder was created using <code>json.NewEncoder(w)</code>, which will write the JSON output to the response writer <code>w</code>.</li>
<li>The <code>person</code> struct was encoded to JSON and written to the response using <code>encoder.Encode(person)</code>.</li>
<li>If an error occurs during encoding, it is sent back to the client as an HTTP error response with a status code <code>500 Internal Server Error</code>.</li>
</ul>
<h2 id="heading-how-to-parse-json-requests-decoding">How to Parse JSON Requests (Decoding)</h2>
<p>JSON decoding is the process of converting JSON data into Go data structures. </p>
<p>Decoding refers to the process of converting data from a standardized format back into its original form. In computing and data transmission, decoding involves taking encoded data and transforming it into a format that can be easily understood and processed by a specific system or application.</p>
<p>Think of decoding like unpacking a suitcase after a trip. You take the packed suitcase (encoded data) and unpack it, putting each item (data) back to its original place, so that you can use it again.</p>
<p>In the case of JSON decoding, the text-based JSON data is converted back into its original form, such as a Go data structure (like a struct or slice), so that it can be easily accessed and processed by the application.</p>
<p>Some common reasons for decoding data include:</p>
<ul>
<li>Data extraction: Retrieving specific data from a larger encoded dataset.</li>
<li>Data analysis: Converting encoded data into a format that can be easily analyzed or processed.</li>
<li>Data storage: Converting encoded data into a format that can be easily stored in a database or file system.</li>
<li>Data visualization: Converting encoded data into a format that can be easily visualized or displayed.</li>
</ul>
<p>Decoding is essentially the reverse process of encoding, and it's an essential step in many data processing pipelines.</p>
<p>In Golang, we can use the <code>encoding/json</code> package to decode JSON data.</p>
<h3 id="heading-how-to-use-the-unmarshal-function-to-parse-json-requests">How to Use the Unmarshal Function to Parse JSON Requests</h3>
<p>The <code>Unmarshal</code> function is the most commonly used method for decoding JSON data in Golang. It takes a JSON-encoded string as input and returns a Go data structure.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> ( 
    <span class="hljs-string">"encoding/json"</span> 
    <span class="hljs-string">"fmt"</span> 
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> { 
    Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span> 
    Age <span class="hljs-keyword">int</span> <span class="hljs-string">`json:"age"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> { 
    <span class="hljs-keyword">var</span> person Person err := json.NewDecoder(r.Body).Decode(&amp;person)

    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {  
        http.Error(w, err.Error(), http.StatusBadRequest)  
        <span class="hljs-keyword">return</span>
    } 

    fmt.Println(person.Name) 
    <span class="hljs-comment">// Output: John fmt.Println(person.Age) </span>
    <span class="hljs-comment">// Output: 30</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
    http.HandleFunc(<span class="hljs-string">"/"</span>, handler) http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
}
</code></pre>
<h4 id="heading-code-explanation-2">Code Explanation:</h4>
<h6 id="heading-inside-the-handler-1">Inside the handler:</h6>
<ul>
<li>The <code>handler</code> function is an HTTP handler that handles incoming HTTP requests.</li>
<li><code>w http.ResponseWriter</code>: Used to write the response.</li>
<li><code>r *http.Request</code>: Represents the incoming request.</li>
<li>A variable <code>person</code> of type <code>Person</code> was declared.</li>
<li><code>json.NewDecoder(r.Body).Decode(&amp;person)</code>: This decodes the JSON request body into the <code>person</code> struct.</li>
<li>If an error occurs during decoding, it sends back an HTTP 400 error response with a status code <code>400 Bad Request</code>.</li>
<li>If decoding is successful, the <code>person</code> struct fields <code>Name</code> and <code>Age</code> are printed using <code>fmt.Println</code>.</li>
</ul>
<h3 id="heading-how-to-use-the-newdecoder-function-for-json-decoding">How to Use the NewDecoder Function for JSON Decoding</h3>
<p>The <code>NewDecoder</code> function is also used to decode JSON data from a reader, such as a file or network connection.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> ( 
    <span class="hljs-string">"encoding/json"</span> 
    <span class="hljs-string">"fmt"</span> 
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> { 
    Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span> 
    Age <span class="hljs-keyword">int</span> <span class="hljs-string">`json:"age"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">handler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> { 

    decoder := json.NewDecoder(r.Body) 

    <span class="hljs-keyword">var</span> person Person err := decoder.Decode(&amp;person) 

    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {  
        http.Error(w, err.Error(), http.StatusBadRequest)  
        <span class="hljs-keyword">return</span> 
       } 

    fmt.Println(person.Name) 
    <span class="hljs-comment">// Output: John fmt.Println(person.Age) </span>
    <span class="hljs-comment">// Output: 30</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
    http.HandleFunc(<span class="hljs-string">"/"</span>, handler) 

    http.ListenAndServe(<span class="hljs-string">":8080"</span>, <span class="hljs-literal">nil</span>)
 }
</code></pre>
<h4 id="heading-code-explanation-3">Code Explanation:</h4>
<h6 id="heading-inside-the-handler-function">Inside the handler function:</h6>
<ul>
<li>The <code>handler</code> function is an HTTP handler that handles incoming HTTP requests.</li>
<li><code>w http.ResponseWriter</code>: Used to write the response.</li>
<li><code>r *http.Request</code>: Represents the incoming request.</li>
</ul>
<h6 id="heading-create-a-decoder">Create a Decoder:</h6>
<ul>
<li><code>decoder := json.NewDecoder(r.Body)</code>: Creates a new JSON decoder that reads from the request body.</li>
</ul>
<h6 id="heading-declare-a-person-variable">Declare a Person Variable:</h6>
<ul>
<li><code>var person Person</code>: Declares a variable <code>person</code> of type <code>Person</code>.</li>
</ul>
<h6 id="heading-decode-json-into-person-struct">Decode JSON into Person Struct:</h6>
<ul>
<li><code>err := decoder.Decode(&amp;person)</code>: Decodes the JSON from the request body into the <code>person</code> struct.</li>
<li>If an error occurs during decoding, it sends an HTTP 400 error response with the status code <code>400 Bad Request</code> and returns from the function.</li>
</ul>
<h6 id="heading-print-the-decoded-values">Print the Decoded Values:</h6>
<ul>
<li><code>fmt.Println(person.Name)</code>: Prints the <code>Name</code> field of the <code>person</code> struct.</li>
<li><code>fmt.Println(person.Age)</code>: Prints the <code>Age</code> field of the <code>person</code> struct.</li>
</ul>
<h3 id="heading-custom-json-marshaling-and-unmarshaling">Custom JSON Marshaling and Unmarshaling</h3>
<p>In some cases, the default JSON encoding and decoding behavior provided by <code>json.Marshal</code> and <code>json.Unmarshal</code> may not be sufficient. For instance, you may need to customize how certain fields are represented in JSON. This is where the <code>json.Marshaler</code> and <code>json.Unmarshaler</code> interfaces come in handy.</p>
<h4 id="heading-how-to-use-json-marshaler">How to use JSON Marshaler</h4>
<p>The <code>json.Marshaler</code> interface allows you to customize the JSON encoding of a type by implementing the <code>MarshalJSON</code> method. This method returns a JSON-encoded byte slice and an error.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p Person)</span> <span class="hljs-title">MarshalJSON</span><span class="hljs-params">()</span> <span class="hljs-params">([]<span class="hljs-keyword">byte</span>, error)</span></span> {
    <span class="hljs-keyword">type</span> Alias Person
    <span class="hljs-keyword">return</span> json.Marshal(&amp;<span class="hljs-keyword">struct</span> {
        Alias
        Age <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"age"`</span>
    }{
        Alias: (Alias)(p),
        Age:   strconv.Itoa(p.Age) + <span class="hljs-string">" years"</span>,
    })
}
</code></pre>
<p>In this example, the <code>Age</code> field is converted to a string with a " years" suffix when encoding to JSON.</p>
<h4 id="heading-how-to-use-json-unmarshaler">How to use JSON Unmarshaler</h4>
<p>The <code>json.Unmarshaler</code> interface allows you to customize the JSON decoding of a type by implementing the <code>UnmarshalJSON</code> method. This method takes a JSON-encoded byte slice and returns an error.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Person)</span> <span class="hljs-title">UnmarshalJSON</span><span class="hljs-params">(data []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-keyword">type</span> Alias Person
    aux := &amp;<span class="hljs-keyword">struct</span> {
        Alias
        Age <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"age"`</span>
    }{Alias: (Alias)(*p)}

    <span class="hljs-keyword">if</span> err := json.Unmarshal(data, &amp;aux); err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }

    ageStr := strings.TrimSuffix(aux.Age, <span class="hljs-string">" years"</span>)
    age, err := strconv.Atoi(ageStr)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }

    p.Age = age
    p.Name = aux.Name
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<p>In this example, the <code>Age</code> field is converted from a string with a " years" suffix to an integer when decoding from JSON.</p>
<h2 id="heading-trade-offs">Trade-offs</h2>
<p>From the various methods described above for encoding and decoding JSON. Here are the trade-offs for the most commonly used methods:</p>
<h3 id="heading-jsonmarshal-and-jsonunmarshal">json.Marshal and json.Unmarshal:</h3>
<h4 id="heading-pros">Pros:</h4>
<ul>
<li><strong>Ease of Use</strong>: Straightforward for encoding (Marshal) and decoding (Unmarshal) JSON.</li>
<li><strong>Flexibility</strong>: Can be used with various types including structs, maps, slices, and more.</li>
<li><strong>Customization</strong>: Struct tags (<code>json:"name"</code>) allow customization of JSON keys and other options.</li>
</ul>
<h4 id="heading-cons">Cons:</h4>
<ul>
<li><strong>Performance</strong>: May not be the fastest method for very large or complex JSON structures.</li>
<li><strong>Error Handling</strong>: Error messages can sometimes be less descriptive for deeply nested or complex data structures.</li>
</ul>
<h3 id="heading-jsonnewencoder-and-jsonnewdecoder">json.NewEncoder and json.NewDecoder:</h3>
<h4 id="heading-pros-1">Pros:</h4>
<ul>
<li><strong>Stream-Based</strong>: Suitable for encoding/decoding JSON in a streaming manner, which can handle large data sets without consuming a lot of memory.</li>
<li><strong>Flexibility</strong>: Can work directly with <code>io.Reader</code> and <code>io.Writer</code> interfaces, making them useful for network operations and large files.</li>
</ul>
<h4 id="heading-cons-1">Cons:</h4>
<ul>
<li><strong>Complexity</strong>: Slightly more complex to use compared to <code>json.Marshal</code> and <code>json.Unmarshal</code>.</li>
<li><strong>Error Handling</strong>: Similar to <code>json.Marshal</code> and <code>json.Unmarshal</code>, error messages can be less clear for complex structures.</li>
</ul>
<h3 id="heading-custom-marshaler-and-unmarshaler-interfaces-jsonmarshaler-and-jsonunmarshaler">Custom Marshaler and Unmarshaler Interfaces (json.Marshaler and json.Unmarshaler):</h3>
<h4 id="heading-pros-2">Pros:</h4>
<ul>
<li><strong>Customization</strong>: Full control over how types are encoded/decoded. Useful for handling complex types or custom JSON structures.</li>
<li><strong>Flexibility</strong>: Allows for implementing custom logic during marshaling/"unmarshaling."</li>
</ul>
<h4 id="heading-cons-2">Cons:</h4>
<ul>
<li><strong>Complexity</strong>: More complex to implement and use, as it requires writing custom methods.</li>
<li><strong>Maintenance</strong>: Increases the maintenance burden since custom logic needs to be kept in sync with any changes in the struct or data format.</li>
</ul>
<h3 id="heading-use-cases-and-recommendations">Use Cases and Recommendations</h3>
<ul>
<li><strong>Simple Data Structures</strong>: Use <code>json.Marshal</code> and <code>json.Unmarshal</code> for straightforward encoding/decoding of simple data structures.</li>
<li><strong>Large Data Streams</strong>: Use <code>json.NewEncoder</code> and <code>json.NewDecoder</code> for working with large data streams or when interacting with files or network operations.</li>
<li><strong>Custom Requirements</strong>: Implement <code>json.Marshaler</code> and <code>json.Unmarshaler</code> interfaces when you need custom behavior for specific types.</li>
<li><strong>Quick Operations</strong>: Use anonymous structs for quick, throwaway operations where defining a full struct type is unnecessary.</li>
</ul>
<p>Each method has its own strengths and trade-offs, and the best choice depends on the specific requirements of your application.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>In conclusion, mastering JSON encoding and decoding is crucial for developing web applications in Golang. </p>
<p>By understanding the different methods available in the <code>encoding/json</code> package, you can choose the most suitable approach based on your specific requirements.</p>
<p>The <code>Marshal</code> and <code>Unmarshal</code> functions offer simplicity and flexibility for general use, while <code>NewEncoder</code> and <code>NewDecoder</code> provide efficient streaming capabilities for large datasets. </p>
<p>For scenarios that demand customized JSON representations, implementing the <code>json.Marshaler</code> and <code>json.Unmarshaler</code> interfaces gives you fine-grained control over the encoding and decoding processes. </p>
<p>Each method has its own strengths and trade-offs, and knowing when and how to use them will enable you handle JSON data effectively in your applications.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Structure JSON Responses in ChatGPT with Function Calling ]]>
                </title>
                <description>
                    <![CDATA[ By James Charlesworth ChatGPT's Problem With JSON Open up the ChatGPT UI and ask it for some JSON. Chances are you will get a response like you can see in the cover photo above: a JSON object presented to you in markdown format, with some text to eit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-get-json-back-from-chatgpt-with-function-calling/</link>
                <guid isPermaLink="false">66d45f319208fb118cc6cfb7</guid>
                
                    <category>
                        <![CDATA[ chatgpt ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 25 Oct 2023 18:09:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/chatgpt-ui-circled-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By James Charlesworth</p>
<h2 id="heading-chatgpts-problem-with-json">ChatGPT's Problem With JSON</h2>
<p>Open up the <a target="_blank" href="https://chat.openai.com/">ChatGPT UI</a> and ask it for some JSON. Chances are you will get a response like you can see in the cover photo above: a JSON object presented to you in markdown format, with some text to either side explaining what the JSON shows.  </p>
<p>If you try this same prompt in the <a target="_blank" href="https://platform.openai.com/playground">OpenAI Playground</a>, you can see the JSON is enclosed in three backticks (markdown syntax).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/openai-playground-1-1.png" alt="Open AI Playground interface showing a user prompt asking for some JSON" width="600" height="400" loading="lazy">
<em>https://platform.openai.com/playground</em></p>
<p>Now this is great. ChatGPT has gone above and beyond by explaining the response in easy to understand terms – easy to understand, that is...for a human. Not for a machine. Machines need data in a format that sticks to a reliable, consistent, and predictable schema.</p>
<p>Ideally, you'd like to parse the response from ChatGPT in your code and do something useful with it, like this:</p>
<pre><code class="lang-ts"><span class="hljs-comment">// Use the openai package from npm to call ChatGPT</span>
<span class="hljs-keyword">import</span> OpenAI <span class="hljs-keyword">from</span> <span class="hljs-string">"openai"</span>;

<span class="hljs-comment">// Create a new instance of the openai client with our API key</span>
<span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({ apiKey: process.env.OPENAI_KEY });

<span class="hljs-comment">// Call ChatGPT's completions endpoint and ask for some JSON</span>
<span class="hljs-keyword">const</span> gptResponse = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    model: <span class="hljs-string">"gpt-3.5-turbo"</span>,
    temperature: <span class="hljs-number">1</span>,
    messages: [
        {
            role: <span class="hljs-string">"user"</span>,
            content: <span class="hljs-string">"Give me the JSON for an object that represents a cat."</span>
        }
    ],
});

<span class="hljs-comment">// Attempt to read the response as JSON,</span>
<span class="hljs-comment">// Will most likely fail with a SyntaxError...</span>
<span class="hljs-keyword">const</span> json = <span class="hljs-built_in">JSON</span>.parse(gptResponse.choices[<span class="hljs-number">0</span>].message.content);
</code></pre>
<p>But this will only work if <code>gptResponse.choices[0].message.content</code> is valid JSON every time.  </p>
<p>It would also be nice to have JSON returned that reliably sticks to a schema:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">type</span> Cat = {
    name: <span class="hljs-built_in">string</span>,
    colour: <span class="hljs-string">"brown"</span> | <span class="hljs-string">"grey"</span> | <span class="hljs-string">"black"</span>,
    age: <span class="hljs-built_in">number</span>
}

<span class="hljs-comment">// Read the response JSON and type it to our Cat object schema</span>
<span class="hljs-keyword">const</span> json = &lt;Cat&gt;<span class="hljs-built_in">JSON</span>.parse(gptResponse.choices[<span class="hljs-number">0</span>].message.content);
</code></pre>
<p>Not being able to rely on ChatGPT to return valid JSON in a predictable format can introduce bugs into your application, particularly when consistency is key. This becomes a real problem when you're writing code that relies on real-time responses from ChatGPT to trigger specific actions or updates so we need to find a solution. There are a couple of ways we can approach this...</p>
<h2 id="heading-how-prompt-engineering-can-help">How Prompt Engineering Can Help</h2>
<p>One approach to solving this problem is through prompt engineering.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/asking-specifically-2.png" alt="Open AI Playground image showing a system prompt controlling the response format" width="600" height="400" loading="lazy">
<em>https://platform.openai.com/playground</em></p>
<p>Here, we have added some instructions to both the user prompt and the <a target="_blank" href="https://platform.openai.com/docs/guides/gpt/chat-completions-api">system message</a>. The instructions attempt to force the model to return only the JSON we want, with the format we want.  </p>
<p>And for many use cases this works acceptably. You can see from the screenshot above that the "Assistant" response is nothing but JSON, and the JSON does adhere to the schema we described for it.</p>
<p>But this doesn't work 100% of the time.</p>
<p>Here is the <em>exact same</em> pair of prompts with the temperature of the model set above 1. Notice how the <code>colour</code> field in the returned JSON does not now stick to one of the allowed values we specified in the User prompt:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/higher-temperature-1.png" alt="Open AI Playground interface showing the Temperature parameter causing invalid responses at higher values" width="600" height="400" loading="lazy"></p>
<h2 id="heading-function-calling-to-the-rescue">Function Calling to the Rescue</h2>
<p><a target="_blank" href="https://platform.openai.com/docs/guides/gpt/function-calling">Function calling</a> is a new way to use the ChatGPT API. Instead of getting a message back from the language model, you get a request to call a function.  </p>
<p>If you've ever used plugins in the ChatGPT UI, <em>Function Calling</em> is the feature behind the scenes that allow plugins to be integrated with the LLM's responses.</p>
<p>Plugins define the functions that are available to the model and allow it to call those functions in response to user prompts.  </p>
<p>When using the API in your own code, you can also take advantage of function calling to better control the data you get back from the model, including forcing it to return JSON data in a predictable format.</p>
<p>Here is a basic request that uses Function Calling to return a <code>message.function_call</code> object in the response instead of a <code>message.content</code> string.  </p>
<p>Here, we are simply asking ChatGPT to call a function ("getName") and a description of the function inside the <code>functions: []</code> array. We are also instructing ChatGPT that we expect it to call this function in the response by setting the value of <code>function_call</code> to the name of our function.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> gptResponse = <span class="hljs-keyword">await</span> openai.chat.completions.create({
    model: <span class="hljs-string">"gpt-3.5-turbo-0613"</span>,
    messages: [
        {
            role: <span class="hljs-string">"user"</span>,
            content: <span class="hljs-string">"Call the function 'getName' and tell me the result."</span>
        }
    ],
    functions: [
        {
            name: <span class="hljs-string">"getName"</span>,
            parameters: {
                <span class="hljs-keyword">type</span>: <span class="hljs-string">"object"</span>,
                properties: {}
            }
        }
    ],
    function_call: { name: <span class="hljs-string">"getName"</span> }
});

<span class="hljs-comment">// Will print "getName"...</span>
<span class="hljs-built_in">console</span>.log(gptResponse.choices[<span class="hljs-number">0</span>].message.function_call.name);
</code></pre>
<p>It's important to note here that the <code>getName()</code> function does not need to actually exist anywhere in our codebase. All we are doing is telling ChatGPT it exists, and that is it available to be called.</p>
<h3 id="heading-how-to-add-function-arguments">How to add function arguments</h3>
<p>Function calling is great because it makes the response from ChatGPT predictable and structured.  </p>
<p>In the example above we will get an object back in <code>gptResponse.choices[0].message.function_call</code> that will contain details of how ChatGPT wants to execute our (imaginary) function. </p>
<p>This object looks like the below, with the name of the function and a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">stringified</a> version of any function arguments it should be called with:</p>
<pre><code class="lang-json">{
  name: <span class="hljs-string">"functionName"</span>,
  arguments: <span class="hljs-string">"{ \"arg1\": \"value\" }"</span>,
}
</code></pre>
<p>We can take advantage of this second <code>arguments</code> value by describing the shape of the function arguments, and having ChatGPT fill this value in with some JSON that conforms to our shape.</p>
<p>Here is the original example as a function call. Note how we have described the schema of the <code>Cat</code> object to ChatGPT inside the definition of a <code>createCatObject</code> function:</p>
<pre><code class="lang-ts">    <span class="hljs-keyword">type</span> Cat = {
        name: <span class="hljs-built_in">string</span>,
        colour: <span class="hljs-string">"brown"</span> | <span class="hljs-string">"grey"</span> | <span class="hljs-string">"black"</span>,
        age: <span class="hljs-built_in">number</span>
    }

    <span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({ apiKey: process.env.OPENAI_KEY });

    <span class="hljs-keyword">const</span> gptResponse = <span class="hljs-keyword">await</span> openai.chat.completions.create({
        model: <span class="hljs-string">"gpt-3.5-turbo-0613"</span>,
        messages: [
            {
                role: <span class="hljs-string">"user"</span>,
                content: <span class="hljs-string">"Create a new Cat object."</span>
            }
        ],
        functions: [
            {
                name: <span class="hljs-string">"createCatObject"</span>,
                parameters: {
                    <span class="hljs-keyword">type</span>: <span class="hljs-string">"object"</span>,
                    properties: {
                        name: {
                            <span class="hljs-keyword">type</span>: <span class="hljs-string">"string"</span>
                        },
                        colour: {
                            <span class="hljs-keyword">type</span>: <span class="hljs-string">"string"</span>,
                            <span class="hljs-built_in">enum</span>: [<span class="hljs-string">"brown"</span>, <span class="hljs-string">"grey"</span>, <span class="hljs-string">"black"</span>]
                        },
                        age: {
                            <span class="hljs-keyword">type</span>: <span class="hljs-string">"integer"</span>
                        }
                    },
                    required: [<span class="hljs-string">"name"</span>, <span class="hljs-string">"colour"</span>, <span class="hljs-string">"age"</span>]
                }
            }
        ],
        function_call: { name: <span class="hljs-string">"createCatObject"</span> }
    });

    <span class="hljs-keyword">const</span> functionCall = gptResponse.choices[<span class="hljs-number">0</span>].message.function_call;
    <span class="hljs-keyword">const</span> json = &lt;Cat&gt;<span class="hljs-built_in">JSON</span>.parse(functionCall.arguments);
</code></pre>
<p>This completions request will instruct ChatGPT to create a new cat object and send it to the <code>createCatObject()</code> function in a specific format. The last line:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> json = &lt;Cat&gt;<span class="hljs-built_in">JSON</span>.parse(functionCall.arguments);
</code></pre>
<p>parses the arguments from ChatGPT into our <code>Cat</code> type, which mirrors the description we gave the model of our the shape of our expected object.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Function calling with ChatGPT not only brings clarity and predictability to the results but also introduces a paradigm shift in how you can interface with machine learning models. </p>
<p>This structured approach ensures that the responses from ChatGPT are scalable, allowing for easier integration into various applications, whether they be simple web apps or more complex machine learning pipelines.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use JSON Server for Front-end Development ]]>
                </title>
                <description>
                    <![CDATA[ By Juliet Ofoegbu One of the most common responsibilities for front-end developers is handling the data in their front-end applications. You’ll need to be able to retrieve data from an API, manipulate it, and then render it on the screen in a modern ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/json-server-for-frontend-development/</link>
                <guid isPermaLink="false">66d45f67b3016bf139028d5a</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 21 Aug 2023 13:54:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/Cover-image-for-my-json-server-article-on-freecodecamp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Juliet Ofoegbu</p>
<p>One of the most common responsibilities for front-end developers is handling the data in their front-end applications. You’ll need to be able to retrieve data from an API, manipulate it, and then render it on the screen in a modern web application for user interactions. </p>
<p>Efficient communication between the front-end and back-end is crucial for creating seamless and responsive applications.</p>
<p>Now imagine a scenario where you're working with a backend developer on a project and you're waiting on the API endpoint in order to connect to your frontend. There's a great tool that front-end developers can use to create a mock or dummy API during the development phase. This tool is called a "JSON Server". </p>
<p>In this article, you’ll learn how to use JSON servers for data storage in your React applications. You'll learn about the features and benefits, and a practical implementation in a front-end project. </p>
<p>The application will enable users to view a list of users and their details. The user's data will be created using JSON Server in a JSON file in the frontend application.</p>
<h2 id="heading-what-is-json-server">What is JSON Server?</h2>
<p>JSON is an acronym for JavaScript Object Notation. JSON Server is a lightweight and easy-to-use Node.js tool that simulates a <a target="_blank" href="https://www.freecodecamp.org/news/what-is-rest-rest-api-definition-for-beginners/">RESTful</a> API using a JSON file as the data source. With JSON Server, front-end developers can create mock APIs without the need to write complex server-side code, or when a backend API isn't ready yet. </p>
<p>This mock API sends requests to an endpoint that will be provided. It responds to HTTP requests, and this makes it ideal for rapid development for front-end developers. JSON Server also enables developers to perform CRUD operations and saves data in JSON files. JSON comes in a key-value pair and is written in this format:</p>
<pre><code class="lang-json">{  
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Jane"</span>,   
  <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>,   
  <span class="hljs-attr">"gender"</span>: <span class="hljs-string">"Female"</span>
}
</code></pre>
<p>The "name", "age", and "gender" are called <strong>properties</strong> and the "Jane", "30", and "female" are the <strong>values</strong> of each of the properties.</p>
<p>JSON data file can come in two formats — the array format and the object with nested objects format.</p>
<p><strong>Array Format</strong></p>
<pre><code class="lang-json">[
  {
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">25</span>
  },
  {
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Jane Smith"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">40</span>
  }
]
</code></pre>
<p><strong>Object with Nested Objects Format</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"users"</span>: {
    <span class="hljs-attr">"1"</span>: {
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
      <span class="hljs-attr">"age"</span>: <span class="hljs-number">25</span>
    },
    <span class="hljs-attr">"2"</span>: {
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Jane Smith"</span>,
      <span class="hljs-attr">"age"</span>: <span class="hljs-number">30</span>
    }
  }
}
</code></pre>
<h2 id="heading-features-of-json-server">Features of JSON Server</h2>
<p>Here are some of the features of JSON Server:</p>
<ul>
<li>It is easy and quick to set up. It is also user-friendly for front-end developers and newbie back-end developers.</li>
<li>It supports common HTTP methods like the GET, POST, PUT, and DELETE methods, just like a real backend API server would.</li>
<li>With JSON Server, you can perform Create, Read, Update, Delete (CRUD) operations on data to build an interactive application.</li>
<li>JSON Server offers developers the ability to create custom routes to handle more complex scenarios.</li>
</ul>
<h2 id="heading-benefits-of-using-json-server">Benefits of Using JSON Server</h2>
<p>Here are some of the benefits of using JSON Server:</p>
<ul>
<li>JSON Server grants front-end developers the ability to quickly create functional API prototypes that can be tested and modified while waiting for the backend server to be ready.</li>
<li>Front-end developers can use JSON Server to simulate different scenarios, and error cases during testing to enhance their application.</li>
</ul>
<h2 id="heading-how-to-set-up-json-server-in-an-application">How to Set up JSON Server in an Application</h2>
<p>You'll need <a target="_blank" href="https://nodejs.org/en">Node.js</a> and <a target="_blank" href="https://www.npmjs.com/">npm</a> installed on your system, as they're both prerequisites for this setup. </p>
<p>Follow these steps to set up and use JSON Server in your frontend application:</p>
<h3 id="heading-step-1-install-json-server">Step #1 - Install JSON Server</h3>
<p>To install JSON Server in your application, navigate to your project directory in your terminal or command prompt and type in this command: <code>npm install -g json-server</code>. </p>
<p>This will install the JSON server globally on your system. If you want to install it locally for just a particular project instead, use this command: <code>npm i json-server</code>.</p>
<h3 id="heading-step-2-create-a-json-file">Step #2 - Create a JSON File</h3>
<p>Create a JSON file in your project directory that will act as the data source. This JSON file should have a <code>.json</code> file extension. What do I mean? Let's say you want your JSON file name to be 'db', it means you'll create a file called <strong>db.json</strong>.</p>
<h3 id="heading-step-3-create-data">Step #3 - Create Data</h3>
<p>Define your data inside the JSON file. This JSON data can be an array of objects or an object with nested objects. Each object represents a data entity and should each have a unique id. </p>
<h3 id="heading-step-4-start-the-server">Step #4 - Start the Server</h3>
<p>Start up the JSON Server by typing this command into your terminal: <code>json-server --watch db.json</code>. This will run on "https://localhost:3000" by default. You can change the port it's running on by specifying a different port number when starting the server using the <code>--port</code> flag. </p>
<p>For example, if you want your server to run on port 8000 instead of the default (3000), use this command while starting the server: <code>json-server --watch db.json --port 8000</code>. You can then view this in your browser on port 8000.</p>
<p>JSON Server will automatically generate RESTful endpoints based on the data you defined in your JSON file. </p>
<p>If you have a JSON file with an array of "users", this is the endpoint that will be automatically generated by the JSON Server:</p>
<ul>
<li>GET  /users - This retrieves a list of all resource entities of users.</li>
<li>GET /users/:id - This retrieves a specific user by its id.</li>
<li>POST /users - This creates a new user.</li>
<li>PUT /users/:id - This updates a user based on a specified id.</li>
<li>DELETE /users/:id - This deletes a user based on the specified id.</li>
</ul>
<p>This pattern makes it easy to interact with the mock API in a RESTful manner just like one would do with a real backend API.</p>
<h2 id="heading-how-to-build-a-simple-front-end-application-using-json-server">How to Build a Simple Front-end Application Using JSON Server</h2>
<p>To further understand how to use the JSON Server in a real project, let's take a look at an example. You'll build a simple React.js application that displays users' data from a JSON data file using the JSON server on the front end. </p>
<p>Ready? Let's get started. Here's a quick look at the app you'll build by the end of this article.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/json-2.png" alt="User data app homepage" width="600" height="400" loading="lazy">
<em>User data app home page</em></p>
<p>This app will have just two pages. The first page is displayed above, and it is a list of users with their names and email addresses. The other page will contain more details about each user based on the user id when the <strong>View full details</strong> button is clicked.</p>
<h3 id="heading-installing-dependencies">Installing Dependencies</h3>
<p>Create a React app using CRA or Vite (recommended). I made use of the yarn package manager to create my app using this command: <code>yarn create vite</code>. Choose a project name and select "React" as the framework and "Typescript" as the variant. You can select JavaScript as your variant instead if you wish. </p>
<p>Once this is done, navigate to your project and use the <code>yarn</code> command to install the dependencies. After it has successfully installed the dependencies, run your development server with this command: <code>yarn run dev</code>. Open up your browser, paste the URL (http://127.0.0.1:5173/) and you'll see your app running on the browser.</p>
<p>Install the JSON server in your application by using this command: <code>npm install -g json-server</code> for global installation, or the <code>npm i json-server</code> command for local installation.</p>
<p>The last package to install is react-router to allow page navigation using this command: <code>npm i react-router-dom</code>. </p>
<h3 id="heading-folder-structure">Folder Structure</h3>
<p>Now you want your application to have a neat folder structure so follow these guidelines:</p>
<p>First, create a <strong>data</strong> folder in the root directory of your project. Inside this data folder, you'll create a JSON file called <strong>db.json</strong>. This is where the JSON data will be defined. </p>
<p>Next, in the <strong>src</strong> directory, create a <strong>components</strong> folder. In this folder, you'll create 3 files: <strong>Home.tsx</strong>, <strong>UserDetails.tsx</strong>, and <strong>UserList.tsx</strong>. These are the components that will render the logic and UI of the application. </p>
<p>In the <strong>src</strong> directory, create a file named <strong>useFetch.tsx</strong>. This file will contain the code for the API implementation. The main component of your application — the <strong>App.tsx</strong> file — is where you'll handle pages routing.</p>
<h3 id="heading-building-the-app">Building the App</h3>
<p>The first component you'll be modifying is the <strong>App.tsx</strong> file. Paste the following lines of code in the component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/Home'</span>;
<span class="hljs-keyword">import</span> UserDetails <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/UserDetails'</span>;
<span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router, Routes, Route } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">Home</span> /&gt;</span>} /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/users/:id"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">UserDetails</span> /&gt;</span>} /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Router</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>This is just to provide routes for the application. </p>
<p>Go to your <strong>db.json</strong> file and define your JSON data inside. Paste these lines of code into the JSON file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"users"</span>: [
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Juliet Oma"</span>,
      <span class="hljs-attr">"email"</span>: <span class="hljs-string">"julie@yahoo.com"</span>,
      <span class="hljs-attr">"number"</span>: <span class="hljs-string">"08100000000"</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"James Williams"</span>,
      <span class="hljs-attr">"email"</span>: <span class="hljs-string">"jameswilly@gmail.com"</span>,
      <span class="hljs-attr">"number"</span>: <span class="hljs-string">"08111111111"</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">3</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Ahmed Ali"</span>,
      <span class="hljs-attr">"email"</span>: <span class="hljs-string">"ahmedali012@gmail.com"</span>,
      <span class="hljs-attr">"number"</span>: <span class="hljs-string">"09022222222"</span>
    },
    {
      <span class="hljs-attr">"id"</span>: <span class="hljs-number">4</span>,
      <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Grace Funsho"</span>,
      <span class="hljs-attr">"email"</span>: <span class="hljs-string">"gracefunsho@gmail.com"</span>,
      <span class="hljs-attr">"number"</span>: <span class="hljs-string">"09033333333"</span>
    }
  ]
}
</code></pre>
<p>Start up your JSON server using this command: <code>json-server --watch db.json --port 8000</code>. This command will watch the db.json file and wrap the API endpoint running on port 8000. If you check your terminal, this is how it will look like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/json-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If you copy out that <strong>Resources</strong> URL (http://localhost:8000/users) provided in the terminal and open it up on your browser, you'll see a JSON data displaying all the user data you defined in your <strong>db.json</strong> file. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/json-3-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>JSON file on the browser</em></p>
<p>Next, you'll need to write code to implement the API. This will be done in the <strong>useFetch.tsx</strong> file. This is basically a custom React Hook that you'll create to handle asynchronous data fetching from a given URL.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

interface UseFetchResult {
    <span class="hljs-attr">data</span>: any | <span class="hljs-literal">null</span>;
    isPending: boolean;
    error: any | <span class="hljs-literal">null</span>;
}

<span class="hljs-keyword">const</span> useFetch = (url: string): <span class="hljs-function"><span class="hljs-params">UseFetchResult</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> [data, setData] = useState&lt;any | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>);
    <span class="hljs-keyword">const</span> [isPending, setIsPending] = useState&lt;boolean&gt;(<span class="hljs-literal">true</span>);
    <span class="hljs-keyword">const</span> [error, setError] = useState&lt;any | <span class="hljs-literal">null</span>&gt;(<span class="hljs-literal">null</span>);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            fetch(url)
                .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> {
                    <span class="hljs-keyword">if</span> (!res.ok) {
                        <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Error fetching users data'</span>);
                    }
                    <span class="hljs-keyword">return</span> res.json();
                })
                .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
                    setData(data);
                    setIsPending(<span class="hljs-literal">false</span>);
                    setError(<span class="hljs-literal">null</span>);
                })
                .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> {
                    setIsPending(<span class="hljs-literal">false</span>);
                    setError(err.message);
                });
        }, <span class="hljs-number">1000</span>);
    }, [url]);

    <span class="hljs-keyword">return</span> { data, isPending, error };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> useFetch;
</code></pre>
<p>Let's breakdown the code above.</p>
<p>First, you'll need to import two hooks. The <code>useState</code> &amp; <code>useEffect</code> hooks will be used to manage states and perform side effects in the custom hook.</p>
<p>While setting up my React project, I selected Typescript as a variant, so my app is using Typescript. If you did the same, you'll need to declare an interface named <code>useFetchResult</code> which specifies the structure of the result object that the <code>useFetch</code> hook will return. It contains three properties: <code>data</code>, <code>isPending</code>, and <code>error</code>.</p>
<p>The line of code <code>const useFetch = (url: string): UseFetchResult =&gt; { ... }</code> defines the <code>useFetch</code> custom hook. It takes a url parameter of type string and returns an object that complies with the <code>UseFetchResult</code> interface.</p>
<p>Next, you need to initialize three variables using the <code>useState</code> hook: <code>data</code> to store the fetched data, <code>isPending</code> to indicate whether the data fetching is in progress, and <code>error</code> state to store any error that occurs during the fetching process. Each has an initial value of <code>null</code>, <code>true</code>, and <code>null</code> respectively.</p>
<p>The <code>useEffect</code> hook is used to perform the data fetching when the URL changes. It runs after the initial render and whenever the URL dependency changes. Inside the <code>useEffect</code> function, a <code>setTimeOut</code> is defined to simulate a 1000 milliseconds (1 second) delay before initiating the data fetching. </p>
<p>The <code>fetch</code> method is used to make a GET request to the specified UR:. The response is checked using <code>res.ok</code>. If the response is not ok, it throws an error. The response is then converted to JSON using the <code>res.json()</code> method and stored in the data variable. The <code>isPending</code> state is set to <code>false</code> to indicate that the data fetching is complete, and the error state is set to null to clear previous error.</p>
<p>If any error occurs during the data fetching process, it is caught in the <code>.catch</code> block. <code>isPending</code> is set to false, and then the <code>error</code> state is updated with the error message.</p>
<p>The custom hook returns an object containing the <code>data</code>, <code>isPending</code>, and <code>error</code> states, allowing other components to access the fetched data and its state.</p>
<h3 id="heading-creating-the-list-of-users-in-tabular-form">Creating the List of Users in Tabular form</h3>
<p>This is basically the component that will display all user's info in a table. In your <strong>UserList.tsx</strong> file, paste these lines of code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;

interface User {
    <span class="hljs-attr">id</span>: number;
    name: string;
    email: string;
    number: string;
}

interface UserListProps {
    <span class="hljs-attr">users</span>: User[];
    name: string;
}

<span class="hljs-keyword">const</span> UserList: React.FC&lt;UserListProps&gt; = <span class="hljs-function">(<span class="hljs-params">{ users, name }</span>) =&gt;</span> {

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Users List<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
                                <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Name<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                                    <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Details<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                                <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
                            <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
                            <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
                                {users.map((user) =&gt; (
                                    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span>
                                        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
                                          <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{user.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                                        <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>

                                        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
                                            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{user.email}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                                        <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>

                                        <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
                                            <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>`/<span class="hljs-attr">users</span>/${<span class="hljs-attr">user.id</span>}`}&gt;</span>
                                                <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
                                                    View full details
                                                <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                                            <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
                                        <span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
                                    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
                                ))}
                            <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
                        <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> UserList;
</code></pre>
<p>We started by importing <code>Link</code> from the <code>react-router-dom</code> library. </p>
<p>The next line of code is the <code>interface User</code>, a typescript interface that defines the structure of a user object which has four properties with each property having a specified data type.</p>
<p>Then comes the interface <code>UserListProps</code> which defines the structure of an object that has two properties — <code>users</code> and <code>name</code>. <code>users</code> is an array of objects that matches the <code>User</code> interface.</p>
<p>This component takes an object with the <code>userListProps</code> interface as an argument, destructures <code>users</code> from it, and uses it as props in the component.</p>
<p>Then you have the JSX element to display the list of users in tabular format. We mapped through the list using the <code>map</code> method to render each user in a row. </p>
<p>We then added a button to each row that triggers navigation to a specific route (<code>/users/${user.id}</code>). These routes will display the detailed information of the user whose <code>id</code> is provided as part of the URL. </p>
<p>We used a template literal to create a dynamic URL that includes the <code>user.id</code> value.</p>
<p>Your app is gradually taking shape.</p>
<h3 id="heading-rendering-user-list-on-the-browser">Rendering User List on the Browser</h3>
<p>The next component you'll be working on is the <strong>Home.tsx</strong> component. This is where the user list will be rendered on the screen and it's the home page of your application. </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> UserList <span class="hljs-keyword">from</span> <span class="hljs-string">'./UserList'</span>;
<span class="hljs-keyword">import</span> useFetch <span class="hljs-keyword">from</span> <span class="hljs-string">'../useFetch'</span>;

<span class="hljs-keyword">const</span> Home = (): JSX.Element =&gt; {
    <span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: users, isPending, error } = useFetch(<span class="hljs-string">'http://localhost:8000/users'</span>)

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
            {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{error}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
            {isPending &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading users...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
            {users &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">UserList</span> <span class="hljs-attr">users</span>=<span class="hljs-string">{users}</span> /&gt;</span>}
        <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>We first imported the <code>UserList</code> component and the <code>useFetch</code> custom hook from where they're located in the project directory.</p>
<p>The <code>const { data: users, isPending, error } = useFetch('http://localhost:8000/users')</code> line of code calls the <code>useFetch</code> custom hook to fetch data from the specified URL (http://localhost:8000/users). The hook returns an object with three properties: <code>data</code> (the fetched users), <code>isPending</code> (loading status), and <code>error</code> (error message).</p>
<p>We rendered the UI with the JSX elements. If the <code>error</code> state has a value, it renders a paragraph element containing the error message. If the <code>isPending</code> state is <code>true</code>, it renders a paragraph element indicating that users are being loaded. If the <code>users</code> state has data (if it is not <code>null</code>), it renders the <code>UserList</code> component and passes the <code>users</code> data as a prop.</p>
<h3 id="heading-displaying-users-full-details">Displaying Users Full Details</h3>
<p>We want to add an additional functionality where you can view more details about a particular user on another page by clicking on the <strong>View full details</strong> button that is in same row with their name. </p>
<p>To do that, paste these lines of code in the <code>UserDetails.tsx</code> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useParams } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;
<span class="hljs-keyword">import</span> useFetch <span class="hljs-keyword">from</span> <span class="hljs-string">'../useFetch'</span>;

<span class="hljs-keyword">const</span> UserDetails = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> { id } = useParams();
    <span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: user, error, isPending } = useFetch(<span class="hljs-string">"http://localhost:8000/users/"</span> + id);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
                {isPending &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading user details...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

                {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{error}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}

                {user &amp;&amp; (
                    <span class="hljs-tag">&lt;&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>User {user.id} details<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>{user.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{user.email}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{user.number}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
                    <span class="hljs-tag">&lt;/&gt;</span>
                )}
            <span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> UserDetails;
</code></pre>
<p>From the code above, we imported the <code>useParams</code> hook from the <code>react-router-dom</code> library. This allows access to URL parameters. We also imported the <code>useFetch</code> custom hook.</p>
<p>The <code>const { id } = useParams();</code> uses the <code>useParams</code> hook to extract the <code>id</code> parameter from the URL. This is typically used in routes like <code>/users/:id</code>.</p>
<p>The next line of code after that calls the <code>useFetch</code> custom hook to fetch data from a specific user's URL based on the extracted <code>id</code> parameter. The hook returns an object with <code>data</code>, <code>error</code>, and <code>isPending</code> properties.</p>
<p>Then comes the JSX elements to render the users' details. <code>{isPending &amp;&amp; &lt;p&gt;Loading user details...&lt;/p&gt;}</code> renders a paragraph indicating that the user details are being loaded if <code>isPending</code> is <code>true</code>. </p>
<p><code>{error &amp;&amp; &lt;p&gt;{error}&lt;/p&gt;}</code> will render a paragraph displaying an error message, if there is an error. While <code>{user &amp;&amp; (...)}</code> renders some user details like <code>id</code>, <code>name</code>, <code>email</code>, and <code>number</code>, if the data is available.</p>
<p>When you go back to your browser, you'll see a list of user data in a table. Each user row in the table will have a button that you can click to open up a page for you to see that specific user's full details. </p>
<p>Now this app won't look so good because it hasn't been styled. So go ahead and style your application using whatever styling technique you want to use. A quick view of my app after styling:</p>
<p><div class="embed-wrapper"><iframe src="https://giphy.com/embed/XPVIQLbhPVlXWHSAyh" width="480" height="258" class="giphy-embed" title="Embedded content" loading="lazy"></iframe></div></p><p><a href="https://giphy.com/gifs/XPVIQLbhPVlXWHSAyh">via GIPHY</a></p><p></p>
<p>I know the UI isn't so great but the main focus here was the functionality. Notice how I added a loading animation that displays when the user list and details are waiting to be fetched? You can do this by using an animation library like Framer motion or creating a spinner component. </p>
<p>The loading animation or spinner will be rendered while data is waiting to be fetched instead of just a "Loading....' text. This can make your app look better and help you with user engagement.</p>
<p>You can modify the user data or add more details to your user list like users' job description, their title, and so on in your <strong>db.json</strong> file and you'll see the changes reflected in the list on the browser. </p>
<p>This app sends a request to the API endpoint provided when you start the JSON server and displays the response on the browser. That's basically how a real backend API server works. In this case, we were able to achieve our functionality using JSON Server.</p>
<p>It is important to know that this JSON mock API can't be used at the production stage. It can only be used in the development stage to create dummy JSON data. This means that you can't ship it to production as the JSON data file only runs on a localhost port.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>That's all for this article. Here, you learned about the JSON server and how to use it in a front-end React.js application.</p>
<p>You can also perform full CRUD operations with this data from your JSON file on your front end. In this article, I only demonstrated the <strong>Read</strong> operation. This app can be further improved to enable people <strong>Create</strong> users, <strong>Update</strong> users, and <strong>Delete</strong> users from the JSON database.</p>
<p>If you're looking to learn how to implement a real third-party API in your React application, check out <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-apis-in-web-development/">my previous article</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the JSON Module in Python – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ JSON (JavaScript Object Notation) is a popular, lightweight data interchange standard. It represents data structures made up of key-value pairs that's quite straightforward and human-readable.  JSON has become the industry standard for data interchan... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-the-json-module-in-python/</link>
                <guid isPermaLink="false">66ba0ea7d14c87384322b695</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ashutosh Krishna ]]>
                </dc:creator>
                <pubDate>Mon, 05 Jun 2023 22:51:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/06/json-module.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON (JavaScript Object Notation) is a popular, lightweight data interchange standard. It represents data structures made up of key-value pairs that's quite straightforward and human-readable. </p>
<p>JSON has become the industry standard for data interchange between online services. And it's widely utilized in modern programming languages, including Python.</p>
<p>JSON data is frequently expressed as nested dictionaries, lists, and scalar values such as texts, numbers, booleans, and null. It is named JSON because it closely mimics the syntax used in JavaScript objects.</p>
<p>In this tutorial, you will explore the JSON module in Python and learn how to effectively work with JSON data.</p>
<h2 id="heading-pythons-built-in-json-module">Python's Built-in JSON Module</h2>
<p>JSON plays an important role in Python programming because it allows efficient data serialization and deserialization. It enables Python programs to effortlessly communicate with web services, exchange data, and store structured information. </p>
<p>Developers can use JSON to seamlessly link their Python programs with a variety of APIs, databases, and external systems that use JSON for data representation.</p>
<p>If you're looking to learn how to interact with web services using Python, check out <a target="_blank" href="https://blog.ashutoshkrris.in/how-to-interact-with-web-services-using-python">my tutorial on the requests module</a>.</p>
<p>The built-in JSON module in Python provides a powerful set of methods and classes that make working with JSON data simple. Developers can use it to encode Python objects into JSON strings and decode JSON strings back into Python objects.</p>
<h2 id="heading-how-to-store-json-data-in-a-file">How to Store JSON Data in a File</h2>
<p>When working with JSON data in Python, you'll often need to save the data or share it with others. Storing JSON data in a file enables quick retrieval and data persistence. </p>
<p>In this section, you'll learn how to use Python's <code>json.dump()</code> function to save JSON data to a file. This process involves serializing the JSON data and saving it to a file, which you can subsequently read and use as needed.</p>
<h3 id="heading-the-jsondump-function">The <code>json.dump()</code> function</h3>
<p>The <code>json.dump()</code> function in Python allows you to store JSON data directly into a file. This function takes two parameters: the data to be serialized and the file object where the data will be written.</p>
<p>To write JSON data to a file, you need to follow a few steps. First, you need to open a file in write mode, specifying the file path. Then, you can use the <code>json.dump()</code> function to serialize the data and write it to the file. Finally, you need to close the file to ensure that all the data is properly saved.</p>
<p>Let's learn how to store data in a file using the horoscope API response as an example.</p>
<p>Assume you have made a GET request to the following URL: <a target="_blank" href="https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&amp;day=today">https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&amp;day=today</a>, which provides the daily horoscope for the Capricorn sign.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Make the GET request to the horoscope API</span>
response = requests.get(<span class="hljs-string">"https://horoscope-app-api.vercel.app/api/v1/get-horoscope/daily?sign=capricorn&amp;day=today"</span>)
data = response.json()  <span class="hljs-comment"># Convert the response to JSON</span>

<span class="hljs-comment"># Store the JSON data in a file</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"horoscope_data.json"</span>, <span class="hljs-string">"w"</span>) <span class="hljs-keyword">as</span> file:
    json.dump(data, file)

print(<span class="hljs-string">"Data stored successfully!"</span>)
</code></pre>
<p>In the code above, you use the <code>requests</code> library to make a GET request to the <a target="_blank" href="https://blog.ashutoshkrris.in/how-to-create-a-horoscope-api-with-beautiful-soup-and-flask">Horoscope API</a>. You then extract the JSON data from the response using the <code>.json()</code> method. Finally, you open a file named <code>horoscope_data.json</code> in write mode using the <code>with</code> statement, and you use <code>json.dump()</code> to store the data in the file.</p>
<p>Check out <a target="_blank" href="https://blog.ashutoshkrris.in/how-to-know-your-horoscope-using-python">this tutorial</a> to learn how to find out your horoscope using Python.</p>
<p>If you open the <code>horoscope_data.json</code> file, you'll see contents similar to below:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"date"</span>: <span class="hljs-string">"Jun 3, 2023"</span>,
    <span class="hljs-attr">"horoscope_data"</span>: <span class="hljs-string">"The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."</span>
  },
  <span class="hljs-attr">"status"</span>: <span class="hljs-number">200</span>,
  <span class="hljs-attr">"success"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<h2 id="heading-how-to-retrieve-data-from-a-json-file">How to Retrieve Data from a JSON File</h2>
<p>You'll often need to read data from a JSON file. For example, you may need to read configuration settings from a JSON file. Python's JSON module provides the <code>json.load()</code> function, which allows you to read and deserialize JSON data from a file. </p>
<p>In this section, you will learn how to use the <code>json.load()</code> function to retrieve JSON data from a file and work with it in your Python programs.</p>
<h3 id="heading-the-jsonload-function">The <code>json.load()</code> function</h3>
<p>The <code>json.load()</code> function accepts a file object as an argument and returns deserialized JSON data in the form of Python objects such as dictionaries, lists, strings, numbers, booleans, and null values.</p>
<p>To read JSON data from a file, you need to open the file in read mode, extract the data using the <code>json.load()</code> function, and store it in a variable for further processing. It's important to ensure that the file being read contains valid JSON data – otherwise, it may raise an exception.</p>
<p>Let's see how you can retrieve the data from the previously created <code>horoscope_data.json</code> file:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Retrieve JSON data from the file</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"horoscope_data.json"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> file:
    data = json.load(file)

<span class="hljs-comment"># Access and process the retrieved JSON data</span>
date = data[<span class="hljs-string">"data"</span>][<span class="hljs-string">"date"</span>]
horoscope_data = data[<span class="hljs-string">"data"</span>][<span class="hljs-string">"horoscope_data"</span>]

<span class="hljs-comment"># Print the retrieved data</span>
print(<span class="hljs-string">f"Horoscope for date <span class="hljs-subst">{date}</span>: <span class="hljs-subst">{horoscope_data}</span>"</span>)
</code></pre>
<p>In the code above, you open the file <code>horoscope_data.json</code> in read mode using the <code>with</code> statement. You then use the <code>json.load()</code> function to deserialize the JSON data from the file into the data variable. Finally, you access specific fields of the JSON data (e.g., "date" and "horoscope_data") and process them as needed.</p>
<h2 id="heading-how-to-format-the-json-output">How to Format the JSON Output</h2>
<p>When you read data from a JSON file and print it, the output is displayed as a single line, which may not resemble the structured format of JSON.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Retrieve JSON data from the file</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"horoscope_data.json"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> file:
    data = json.load(file)

print(data)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'data'</span>: {<span class="hljs-string">'date'</span>: <span class="hljs-string">'Jun 3, 2023'</span>, <span class="hljs-string">'horoscope_data'</span>: <span class="hljs-string">'The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up.'</span>}, <span class="hljs-string">'status'</span>: 200, <span class="hljs-string">'success'</span>: True}
</code></pre>
<h3 id="heading-the-jsondumps-function">The <code>json.dumps()</code> function</h3>
<p>The JSON module provides you with a <code>json.dumps()</code> function to serialize Python objects into a JSON formatted string. It provides various options for customization, including formatting the output to make it more human-readable.</p>
<p>The <code>json.dumps()</code> function provides several <a target="_blank" href="https://docs.python.org/3/library/json.html#json.dumps">options</a> to customize the output. The most commonly used is the <code>indent</code> which allows you to specify the number of spaces used for indentation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Retrieve JSON data from the file</span>
<span class="hljs-keyword">with</span> open(<span class="hljs-string">"horoscope_data.json"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> file:
    data = json.load(file)

<span class="hljs-comment"># Format the data</span>
formatted_data = json.dumps(data, indent=<span class="hljs-number">2</span>)

print(formatted_data)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{
  <span class="hljs-string">"data"</span>: {
    <span class="hljs-string">"date"</span>: <span class="hljs-string">"Jun 3, 2023"</span>,
    <span class="hljs-string">"horoscope_data"</span>: <span class="hljs-string">"The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."</span>
  },
  <span class="hljs-string">"status"</span>: 200,
  <span class="hljs-string">"success"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>As you can see, the JSON data is now formatted with proper indentation, enhancing its readability. This technique can be applied to any JSON data, allowing you to present JSON output in a more organized and visually appealing way.</p>
<h2 id="heading-the-jsontool-command-line-tool">The <code>json.tool</code> Command Line Tool</h2>
<p>Python's JSON module provides a convenient command line tool called <code>json.tool</code> that allows you to format and pretty-print JSON data directly from the command line. It is a useful utility for quickly visualizing the structure and contents of JSON data in a more readable and organized format.</p>
<p>To use <code>json.tool</code>, you can execute the following command in your command-line interface:</p>
<pre><code class="lang-bash">python -m json.tool &lt;input_file&gt; &lt;output_file&gt;
</code></pre>
<p>where:</p>
<ul>
<li><code>python -m json.tool</code> invokes the <code>json.tool</code> module using the Python interpreter.</li>
<li><code>&lt;input_file&gt;</code> represents the path to the JSON file you want to format.</li>
<li><code>&lt;output_file&gt;</code> is an optional argument that specifies the file to which you want to save the formatted JSON output. If not provided, the formatted output will be displayed on the console.</li>
</ul>
<p>Let's say you have a <code>horoscope_data.json</code> file with the following contents:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"data"</span>: {
    <span class="hljs-attr">"date"</span>: <span class="hljs-string">"Jun 3, 2023"</span>,
    <span class="hljs-attr">"horoscope_data"</span>: <span class="hljs-string">"The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."</span>
  },
  <span class="hljs-attr">"status"</span>: <span class="hljs-number">200</span>,
  <span class="hljs-attr">"success"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>Notice that the above JSON file has an indentation of two spaces.</p>
<p>To pretty-print this JSON file using <code>json.tool</code>, you can execute the following command:</p>
<pre><code class="lang-bash">python -m json.tool horoscope_data.json
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"data"</span>: {
        <span class="hljs-attr">"date"</span>: <span class="hljs-string">"Jun 3, 2023"</span>,
        <span class="hljs-attr">"horoscope_data"</span>: <span class="hljs-string">"The forecast today is stormy. You may have sensed that there was some tension clouding the conversation at home. Resentments were left unsaid and subtle power games were played without resolution. Today, Capricorn, it all becomes too unbearable for you. Regardless of the risks involved, you will take measures to clear things up."</span>
    },
    <span class="hljs-attr">"status"</span>: <span class="hljs-number">200</span>,
    <span class="hljs-attr">"success"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>As you can see in the example, executing the <code>json.tool</code> module with the input file path formats the JSON data and displays the formatted output on the console.</p>
<p>You can also redirect the formatted output to an output file by specifying the output file name as the second argument:</p>
<pre><code class="lang-bash">python -m json.tool horoscope_data.json formatted_data.json
</code></pre>
<p>This command formats the JSON data from <code>horoscope_data.json</code> and saves the formatted output to <code>formatted_data.json</code>.</p>
<h2 id="heading-json-encoding-custom-objects">JSON Encoding Custom Objects</h2>
<p>The JSON module in Python allows you to encode and decode custom objects by using JSON encoder and decoder classes. You can define custom serialization and deserialization logic for your objects using these classes.</p>
<p><code>JSONEncoder</code> class allows you to customize the encoding process. To define how your custom object should be encoded into JSON format, you can extend the <code>JSONEncoder</code> and change its <code>default</code> method.</p>
<p>Here's an example of how you can extend the <code>JSONEncoder</code> class and customize the encoding process for a custom object:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name, age</span>):</span>
        self.name = name
        self.age = age


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PersonEncoder</span>(<span class="hljs-params">json.JSONEncoder</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">default</span>(<span class="hljs-params">self, obj</span>):</span>
        <span class="hljs-keyword">if</span> isinstance(obj, Person):
            <span class="hljs-keyword">return</span> {<span class="hljs-string">"name"</span>: obj.name, <span class="hljs-string">"age"</span>: obj.age}
        <span class="hljs-keyword">return</span> super().default(obj)


<span class="hljs-comment"># Create a custom object</span>
person = Person(<span class="hljs-string">"Ashutosh Krishna"</span>, <span class="hljs-number">23</span>)

<span class="hljs-comment"># Encode the custom object using the custom encoder</span>
json_str = json.dumps(person, cls=PersonEncoder)

<span class="hljs-comment"># Print the encoded JSON string</span>
print(json_str)
</code></pre>
<p>In this example, you define a custom class <code>Person</code> with <code>name</code> and <code>age</code> attributes. You then create a subclass of <code>JSONEncoder</code> called <code>PersonEncoder</code> and override its <code>default</code> method. Within the <code>default</code> method, you check if the object being encoded is an instance of <code>Person</code>. If it is, you provide a JSON-serializable representation of the object by returning a dictionary containing the <code>name</code> and <code>age</code> attributes. If the object is not of type <code>Person</code>, you call the <code>default</code> method of the superclass to handle other types.</p>
<p>By using <code>json.dumps</code> and specifying the <code>cls</code> parameter as your custom encoder class <code>PersonEncoder</code>, you can encode the <code>person</code> object into a JSON string. The output will be:</p>
<pre><code class="lang-bash">{<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ashutosh Krishna"</span>, <span class="hljs-string">"age"</span>: 23}
</code></pre>
<p>Similarly, you can specify custom decoding logic in the JSON decoder class, <code>JSONDecoder</code>. To define how JSON data should be decoded into your custom object, extend the <code>JSONDecoder</code> and override its <code>object_hook</code> function.</p>
<h2 id="heading-how-to-create-json-from-a-python-dictionary">How to Create JSON from a Python Dictionary</h2>
<p>You can use the <code>json.dumps()</code> function provided by the JSON module to create JSON from a <a target="_blank" href="https://blog.ashutoshkrris.in/everything-you-need-to-know-about-python-dictionaries">Python dictionary</a>. This function takes a Python object, typically a dictionary, and converts it into a JSON string representation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Python dictionary</span>
data = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ashutosh Krishna"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">23</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"ashutosh@example.com"</span>
}

<span class="hljs-comment"># Convert dictionary to JSON string</span>
json_str = json.dumps(data)

<span class="hljs-comment"># Print the JSON string</span>
print(json_str)
</code></pre>
<p>In this example, you have a Python dictionary <code>data</code> representing some data. By calling <code>json.dumps(data)</code>, you convert the dictionary into a JSON string. The output will be:</p>
<pre><code class="lang-bash">{<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ashutosh Krishna"</span>, <span class="hljs-string">"age"</span>: 23, <span class="hljs-string">"email"</span>: <span class="hljs-string">"ashutosh@example.com"</span>}
</code></pre>
<h2 id="heading-how-to-create-a-python-dictionary-from-json">How to Create a Python Dictionary from JSON</h2>
<p>To create a Python dictionary from JSON data, you can use the <code>json.loads()</code> function provided by the JSON module. This function takes a JSON string and converts it into a corresponding Python object, typically a dictionary.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># JSON string</span>
json_str = <span class="hljs-string">'{"name": "Ashutosh Krishna", "age": 23, "email": "ashutosh@example.com"}'</span>

<span class="hljs-comment"># Convert JSON string to Python dictionary</span>
data = json.loads(json_str)

<span class="hljs-comment"># Access the dictionary values</span>
print(data[<span class="hljs-string">"name"</span>])
print(data[<span class="hljs-string">"age"</span>])
print(data[<span class="hljs-string">"email"</span>])
</code></pre>
<p>In this example, you have a JSON string <code>json_str</code> representing some data. By calling <code>json.loads(json_str)</code>, you convert the JSON string into a Python dictionary. You can then access the values in the dictionary using their respective keys.</p>
<p>The output will be:</p>
<pre><code class="lang-bash">Ashutosh Krishna
23
ashutosh@example.com
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Understanding the Python JSON module is necessary for working with JSON data because it is widely used for data exchange and storage in a variety of applications. </p>
<p>You can efficiently handle JSON data, interface with APIs, and deal with configuration files if you learn how to use the JSON module.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ PostgreSQL and JSON – How to Use JSON Data in PostgreSQL ]]>
                </title>
                <description>
                    <![CDATA[ By Faith Oyama PostgreSQL is a powerful open-source relational database management system (RDBMS). It was initially created as a successor to the Ingres database system and was later named "PostgreSQL" (short for "Post-Ingres SQL"). PostgreSQL is kno... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/postgresql-and-json-use-json-data-in-postgresql/</link>
                <guid isPermaLink="false">66d45ee4787a2a3b05af43ac</guid>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ postgres ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SQL ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 10 May 2023 20:02:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/PostgreSQL-and-JSON-Using-JSON-Data-in-PostgreSQL.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Faith Oyama</p>
<p>PostgreSQL is a powerful open-source relational database management system (RDBMS). It was initially created as a successor to the Ingres database system and was later named "PostgreSQL" (short for "Post-Ingres SQL").</p>
<p>PostgreSQL is known for its robustness, reliability, and scalability, making it a popular choice for large and complex database applications. It offers advanced features such as support for JSON and other non-relational data types as well as support for spatial data.</p>
<p>JSON file support was first introduced in PostgreSQL v9.2, and with every new release, steady improvements are being made.</p>
<p>In this comprehensive guide, you will learn about JSON functions and operators in PostgreSQL. We’ll also go into the basics of storing JSON data in PostgreSQL, how to query JSON data in PostgreSQL to make it readily accessible, and finally, you’ll learn about working with JSON arrays.</p>
<h2 id="heading-what-is-json">What is JSON?</h2>
<p>JSON stands for JavaScript Object Notation. It is a common way to store data, especially in web applications. It is pretty similar to HTML or XML and was made for applications to easily read JSON files.</p>
<p><strong>Key-Value Pairs</strong>: JSON data is written in key-value pairs surrounded by quotes. Here’s an example of a key-value pair “email”: “<a target="_blank" href="mailto:jsonlearning@gmail.com">jsonlearning@gmail.com</a>”. “Email” here is the key, while “<a target="_blank" href="mailto:jsonlearning@gmail.com">jsonlearning@gmail.c</a>om” represents the value. The two are separated by a colon “:”.</p>
<p><strong>Objects:</strong> An object is a key-value pair or pairs enclosed in curly brackets. Whenever a key-value pair is enclosed in curly brackets it becomes an object and can be treated as a single unit. Multiple key-value pairs can be added in an object, separated with a comma.</p>
<p>Example of a JSON object:</p>
<pre><code>{“email” : “jsonlearning@gmail.com”, 
“country” : “United Kingdom”}
</code></pre><p><strong>Arrays:</strong>  Arrays in JSON are a way to store a collection of values within a single JSON object. An array in JSON is represented by square brackets <code>[ ]</code> containing a comma-separated list of values.</p>
<p>Here’s an example of an array in JSON: <code>[ "apple",  "banana",  "cherry"]</code>.</p>
<p>Arrays in JSON can also be nested, meaning that an array can contain other arrays or objects as values. Here's an example of a nested array:</p>
<pre><code>{ <span class="hljs-string">"firstname"</span> : <span class="hljs-string">"Claire"</span>, 
<span class="hljs-string">"location"</span> : <span class="hljs-string">"United Kingdom"</span>, 
<span class="hljs-string">"blog"</span> : [{ <span class="hljs-string">"id"</span> : <span class="hljs-string">"1"</span>, 
<span class="hljs-string">"title"</span> : <span class="hljs-string">"Welcome to my blog"</span> }, 
{ <span class="hljs-string">"id"</span> : <span class="hljs-string">"2"</span>, 
<span class="hljs-string">"title"</span> : <span class="hljs-string">"My first programming language"</span> }]}
</code></pre><p>In this example of nested Arrays, you can see, “blog” is contained in an array, and the array also contains several objects. </p>
<h2 id="heading-jsonb-in-postgresql">JSONB in PostgreSQL</h2>
<h3 id="heading-what-is-the-jsonb-data-type-and-how-is-it-different-from-json">What is the JSONB data type? And how is it different from JSON?</h3>
<p>JSONB (JSON Binary) is a data type in PostgreSQL that allows you to store and manipulate JSON data in a more effective and efficient way than the regular JSON data type.</p>
<p>JSONB stores JSON data in a binary format, which enables faster indexing and query performance compared to the regular JSON data type. This is because the binary format allows for more efficient storage and retrieval of JSON data, particularly when dealing with large or complex JSON objects.</p>
<p>In addition, JSONB supports additional indexing options, such as the ability to index specific keys within a JSON object, which allows for even faster queries.</p>
<p>The regular JSON data type in PostgreSQL stores JSON data as plain text, without any binary encoding or special indexing support. This makes it simpler to use but can result in slower query performance when dealing with large or complex JSON objects.</p>
<h3 id="heading-how-to-create-a-table-with-the-jsonb-data-type">How to create a table with the JSONB data type</h3>
<p>You can create a table and give a column a data type of JSON or JSONB, just like you give a column the data type of Int, VARCHAR, or Double. You can just simply give the column a data type of either JSON or JSONB.</p>
<p>Here’s an example of creating a Table Journal and giving the column “diary_information” the data type JSONB. </p>
<pre><code class="lang-sql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> journal (
  <span class="hljs-keyword">id</span> <span class="hljs-built_in">Int</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span> PRIMARY <span class="hljs-keyword">KEY</span>, <span class="hljs-keyword">day</span> <span class="hljs-built_in">VARCHAR</span>, 
  diary_information JSONB
);
</code></pre>
<p>Because we specified the data type to be of type JSONB, any data held in that column must be a valid JSON.</p>
<h3 id="heading-how-to-insert-json-data-into-tables">How to insert JSON data into tables</h3>
<p>After creating a table and giving our column the data type JSONB, how do we insert values into the column? Remember the data must be in a valid JSON format. </p>
<p>To insert data to our table, we use this statement:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> journal (<span class="hljs-keyword">id</span>, <span class="hljs-keyword">day</span>, diary_information) 
<span class="hljs-keyword">VALUES</span> 
  (
    <span class="hljs-number">1</span>, “Tuesday”, <span class="hljs-string">'{"title": "My first day at work", "Feeling": "Mixed                   feeling"}'</span>
  );
</code></pre>
<p>If we try to retrieve the information using a select statement <code>SELECT * FROM journal</code> we get the following output, meaning the records have been inserted.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/select-from.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the next section, we’ll take a look at some Functions and Operators.</p>
<h2 id="heading-overview-of-json-functions-and-operators">Overview of JSON Functions and Operators</h2>
<p>Functions and operators allow you to store, manipulate, and query data in JSON format in PostgreSQL.</p>
<p>Here are some commonly used PostgreSQL Functions and operators used in working with JSON files:</p>
<ul>
<li><code>-&gt;</code>: This operator allows you to extract a specific value from a JSON object, you specify the key as a “child” to the “parent”. </li>
</ul>
<p>For example:</p>
<p>To retrieve a specific value from a JSON object using the <code>-&gt;</code> operator, use it in a SELECT statement as seen below: </p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> 
  <span class="hljs-keyword">Id</span>, 
  <span class="hljs-keyword">day</span>, 
  diary_information -&gt; <span class="hljs-string">'Feeling'</span> <span class="hljs-keyword">AS</span> Feeling 
<span class="hljs-keyword">FROM</span> 
  journal;
</code></pre>
<p>Something to note here is that this operator extracts the field name, with the quote around it.</p>
<ul>
<li><code>-&gt;&gt;</code>: This operator allows you to extract a JSON object field as text without the quotes around it from a JSON object.</li>
</ul>
<p>For example:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> 
  <span class="hljs-keyword">id</span>, 
  <span class="hljs-keyword">day</span>, 
  dairy_information -&gt;&gt; <span class="hljs-string">'Feeling'</span> <span class="hljs-keyword">as</span> Feeling 
<span class="hljs-keyword">FROM</span> 
  products;
</code></pre>
<p>This will extract the value of the "material" key as text from the "features" column in the "products" table.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/material-products.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><code>json_agg</code>: This function aggregates JSON values into a JSON array.</li>
</ul>
<p>For example, <code>SELECT json_agg(my_column) FROM my_table;</code> will return a JSON array containing the values in the "my_column" column of the "my_table" table.</p>
<ul>
<li><code>jsonb_set</code>: This function updates a JSON object field with a new value. For example:</li>
</ul>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> 
  my_table 
<span class="hljs-keyword">SET</span> 
  json_column = jsonb_set(
    json_column, <span class="hljs-string">'{field_name}'</span>, <span class="hljs-string">'"new_value"'</span>
  ) 
<span class="hljs-keyword">WHERE</span> 
  <span class="hljs-keyword">id</span> = <span class="hljs-number">1</span>;
</code></pre>
<p>To update an existing JSON record, we use the function <code>jsonb_set() ()</code> in an update statement. </p>
<p>For example, to update the record in the table we created earlier, you can run the following code:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">UPDATE</span> 
  journal 
<span class="hljs-keyword">SET</span> 
  diary_information = jsonb_set(
    diary_information, <span class="hljs-string">'{Feeling}'</span>, <span class="hljs-string">'"Excited"'</span>
  ) 
<span class="hljs-keyword">WHERE</span> 
  <span class="hljs-keyword">id</span> = <span class="hljs-number">1</span>;
</code></pre>
<p>This will update the "Feeling" key in the "diary_information" column of the "journal" table with the new value "Excited".</p>
<ul>
<li><code>JSONB_BUILD_OBJECT</code>: Manually inserting JSON values can lead to errors, especially if it’s your first time working with JSON data. But with this function, you can input values without having to worry about curly brackets, colons, and the rest of them.</li>
</ul>
<p>You can use a <code>JSONB_BUILD_OBJECT</code> function to insert a plain text record and this will convert it to JSON data. For example if you run the code:</p>
<pre><code class="lang-sql">JSONB_BUILD_OBJECT('Morning', 'Everybody is annoying today', 'Evening', 'Cannot wait to go home’)
</code></pre>
<p>This will create a value that looks like this:</p>
<pre><code class="lang-sql">{“Morning”: “Everybody is annoying today”, “Evening”: “Cannot wait to go home”}
</code></pre>
<p>Using this function in an insert statement:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> journal (<span class="hljs-keyword">id</span>, <span class="hljs-keyword">day</span>, feeling) 
<span class="hljs-keyword">VALUES</span> 
  (
    <span class="hljs-number">2</span>, 
    <span class="hljs-string">'Wednesday'</span>, 
    JSONB_BUILD_OBJECT(
      <span class="hljs-string">'Tired'</span>, 
      <span class="hljs-string">'Everybody is annoying today'</span>, 
      <span class="hljs-string">'Hungry'</span>, 
      <span class="hljs-string">'Cannot wait to go home’));</span>
</code></pre>
<p>The new record will be added to the table and because we used the <code>JSONB_BUILD__OBJECT</code> function, the values that follow will be in JSON format.</p>
<p>These are the few functions and operators we can cover in this article. You can read more on JSON functions and Operators in PostgreSQL in the official documentation <a target="_blank" href="https://www.postgresql.org/docs/9.5/functions-json.html">here</a>.</p>
<h2 id="heading-how-to-work-with-json-arrays-in-postgresql">How to Work with JSON Arrays in PostgreSQL</h2>
<p>In PostgreSQL, you can store JSON data as a column value in a table, and you can use JSON arrays to store a collection of JSON objects in a single column. </p>
<p>Working with JSON arrays in PostgreSQL involves various operations, such as inserting, querying, and manipulating JSON data. Let's see how those work.</p>
<h3 id="heading-how-to-insert-json-arrays-into-tables">How to insert JSON arrays into tables</h3>
<p>To insert JSON arrays into a table in PostgreSQL, you can use the INSERT INTO statement along with the VALUES clause to specify the JSON array as a string value.</p>
<p>Here's an example:</p>
<p>Suppose you have a table called employees with columns id, name, and skills. The skills column stores an array of JSON objects representing the skills of each employee.</p>
<p>To insert a new employee record with the following details:</p>
<ul>
<li>id: 1</li>
<li>name: John</li>
<li>skills: [{"name": "Python", "level": "Intermediate"}, {"name": "JavaScript", "level": "Expert"}]</li>
</ul>
<p>You can use the following SQL statement:</p>
<pre><code class="lang-sql"><span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> employees (<span class="hljs-keyword">id</span>, <span class="hljs-keyword">name</span>, skills) 
<span class="hljs-keyword">VALUES</span> 
  (
    <span class="hljs-number">1</span>, <span class="hljs-string">'John'</span>, <span class="hljs-string">'[{"name": "Python", "level": "Intermediate"}, {"name":   "JavaScript", "level": "Expert"}]'</span>
  );
</code></pre>
<h3 id="heading-how-to-query-json-arrays-using-json-operators">How to query JSON arrays using JSON operators</h3>
<p>To query JSON arrays in PostgreSQL, you can use the various JSON functions and operators provided by PostgreSQL. These functions allow you to extract specific values or elements from the JSON array and perform various operations on them. Let's look at an example.</p>
<h4 id="heading-how-to-extract-values-from-a-json-array">How to extract values from a JSON array</h4>
<p>Suppose you have a table called employees with a skills column that stores an array of JSON objects representing the skills of each employee.</p>
<p>To extract the names of all employees who have "Python" as one of their skills, you can use the <code>-&gt;&gt;</code> operator to extract the "name" property of each skill object, and the <code>@&gt;</code> operator to check if the resulting array contains the value "Python":</p>
<pre><code class="lang-sql"><span class="hljs-keyword">SELECT</span> 
  <span class="hljs-keyword">name</span> 
<span class="hljs-keyword">FROM</span> 
  employees 
<span class="hljs-keyword">WHERE</span> 
  skills @ &gt; <span class="hljs-string">'[{"name": "Python"}]'</span> :: jsonb
</code></pre>
<p>This is just an example of the many ways in which you can query and manipulate JSON arrays using the JSON operators provided by PostgreSQL.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, PostgreSQL support for JSON provides developers with the ability to simplify data models, enhance application performance, and so much more. This also provides a seamless relationship between relational and non-relational data structures. </p>
<p>You have learned about the JSON and JSONB data types, and what key-value pairs, objects, and arrays are in JSON. You also learned about some operators and functions in PostgreSQL to query data in JSON format.</p>
<p>If you learned a thing or two from this article, please share it with others.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Regular Expressions in a JSON File ]]>
                </title>
                <description>
                    <![CDATA[ JSON stands for JavaScript Object Notation. It is a text-based and lightweight data format for exchanging information between systems, for example, a web server and a web application. JSON files typically contain objects, arrays, strings, and numbers... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-regular-expression-in-json-file/</link>
                <guid isPermaLink="false">66adf155db5636c0b30cba7f</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Mon, 24 Apr 2023 12:38:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/start-graph--11-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON stands for JavaScript Object Notation. It is a text-based and lightweight data format for exchanging information between systems, for example, a web server and a web application.</p>
<p>JSON files typically contain objects, arrays, strings, and numbers. But you can also have regular expressions in a JSON file. And that’s what we are going to take a look at in this article.</p>
<h2 id="heading-how-to-write-regex-inside-json">How to Write RegEx inside JSON</h2>
<p>Remember each entry in a JSON file is a <code>key:value</code> pair surrounded by double quotes. So, if you want to write RegEx inside your JSON file, you need to specify the key and the value and surrounded both with double quotes. </p>
<p>The key can just be an arbitrary name, and the value would be the regex itself. Here’s an example of a JSON file with regular expressions:</p>
<pre><code class="lang-js"><span class="hljs-comment">// data.json file</span>

{
  <span class="hljs-string">"nigeriaPhone"</span>: <span class="hljs-string">"^(\\+?234|0)[789]\\d{9}$"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"^([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_\\-\\.]+)\\.([a-zA-Z]{2,5})$"</span>,
  <span class="hljs-string">"password"</span>: <span class="hljs-string">"^(?=.*[0-9])(?=.*[!@#\\$%^&amp;*])[a-zA-Z0-9!@#\\$%^&amp;*]{8,}$"</span>,
  <span class="hljs-string">"url"</span>: <span class="hljs-string">"^(http|https)://[a-zA-Z0-9-\\.]+\\.[a-zA-Z]{2,5}(/[a-zA-Z0-9-._~:/?#[\\]@!$&amp;'()*+,;=]*)?$"</span>
}
</code></pre>
<p>Writing RegEx inside a JSON file can be useful when you want to use many regular expressions. </p>
<p>Instead of littering your JavaScript, Python file, or any other programming files with regular expressions, you can put all of them inside a JSON file. You can then import the file into your programming language file and use the regular expressions entries.</p>
<p>That takes us to how to use a JSON file inside a programming language. Specifically, we’ll look at how to do that in JavaScript.</p>
<h2 id="heading-how-to-use-a-json-regex-in-a-javascript-file">How to use a JSON RegEx in a JavaScript File</h2>
<p>To use the RegEx from your JSON file inside a JavaScript file, you need to import it first. </p>
<p>An ordinary <code>import something from somefile</code> won't work if you want to import JSON into a JS file. This is the correct way to do it:</p>
<pre><code class="lang-bash">import someName from <span class="hljs-string">'location/file.json'</span> assert { <span class="hljs-built_in">type</span>: <span class="hljs-string">'json'</span> };
</code></pre>
<p>So, I'm going to import the JSON file like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };
</code></pre>
<p>In this case, I’m importing all the entries from the <code>data.json</code> file and naming them <code>validators</code>. This name can be anything. </p>
<p>The <code>assert { type:  'json'}</code> part ensures that what I’m bringing in is a JSON object.</p>
<p>You can then chain any of the keys from the JSON file to <code>validators</code> to see what any of the entries look like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-built_in">console</span>.log(validators.nigeriaPhone); <span class="hljs-comment">// ^(\+?234|0)[789]\d{9}$</span>
<span class="hljs-built_in">console</span>.log(validators.email); <span class="hljs-comment">// ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$</span>
<span class="hljs-built_in">console</span>.log(validators.password); <span class="hljs-comment">// ^(?=.*[0-9])(?=.*[!@#\$%^&amp;*])[a-zA-Z0-9!@#\$%^&amp;*]{8,}$</span>
<span class="hljs-built_in">console</span>.log(validators.url); <span class="hljs-comment">// ^(http|https)://[a-zA-Z0-9-\.]+\.[a-zA-Z]{2,5}(/[a-zA-Z0-9-._~:/?#[\]@!$&amp;'()*+,;=]*)?$</span>
</code></pre>
<p>You can even take this further and test what the regular expressions validate. Here’s how I validated a correct Nigerian phone number:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaNUmber = <span class="hljs-string">'+2348123456789'</span>;

<span class="hljs-keyword">if</span> (naijaNUmber.match(validators.nigeriaPhone)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's a valid Naija phone number"</span>); <span class="hljs-comment">// That's a valid Naija phone number</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's not a valid Naija phone number"</span>);
}
</code></pre>
<p>And here’s how I used the <code>password</code> key to validate a password that is at least eight characters long and contains at least one number and at least one special character:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> pword = <span class="hljs-string">'JohnDoe'</span>;

<span class="hljs-keyword">if</span> (pword.match(validators.password)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"That's Valid password"</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">'Your password must be 8 characters long with at least 1 number and 1 special character'</span>
  ); <span class="hljs-comment">// Your password must be 8 characters long with at least 1 number and 1 special character</span>
}
</code></pre>
<p>Unfortunately, in some situations, you get an error if you decide to use the JSON regex directly without creating a regex out of it. Here’s an example with <code>test()</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-built_in">console</span>.log(naijaPhone.test(<span class="hljs-number">83412343433</span>));

<span class="hljs-comment">/* output: dex.js:4 Uncaught TypeError: naijaPhone.test is not a function
    at index.js:4:24
*/</span>
</code></pre>
<p>You can see that the output does not show it as a regular expression – it is not surrounded by forward slashes. This means you have to create a regex out of it with the regex constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-comment">// Create a regex out of validators.nigeriaPhone;</span>
<span class="hljs-keyword">const</span> naijaNumberRegex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(naijaPhone);
<span class="hljs-built_in">console</span>.log(naijaNumberRegex); <span class="hljs-comment">// Output: /^(\+?234|0)[789]\d{9}$/</span>
</code></pre>
<p>You can see it is now surrounded by forward slashes – that’s a way to identify and even create regex in JavaScript.</p>
<p>Here's how the chrome developer tools distinguishes the two:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/Screenshot-2023-04-24-at-12.22.56.png" alt="Screenshot-2023-04-24-at-12.22.56" width="600" height="400" loading="lazy"></p>
<p>It is with that regex you created that you can test the number:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> validators <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-attr">type</span>: <span class="hljs-string">'json'</span> };

<span class="hljs-keyword">const</span> naijaPhone = validators.nigeriaPhone;
<span class="hljs-built_in">console</span>.log(naijaPhone); <span class="hljs-comment">// Output: ^(\+?234|0)[789]\d{9}$</span>

<span class="hljs-comment">// Create a regex out of validators.nigeriaPhone;</span>
<span class="hljs-keyword">const</span> naijaNumberRegex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(naijaPhone);
<span class="hljs-built_in">console</span>.log(naijaNumberRegex); <span class="hljs-comment">// Output: /^(\+?234|0)[789]\d{9}$/</span>

<span class="hljs-comment">// test it out with the regex</span>
<span class="hljs-built_in">console</span>.log(naijaNumberRegex.test(<span class="hljs-number">83412343433</span>)); <span class="hljs-comment">// output: false</span>
<span class="hljs-built_in">console</span>.log(naijaNumberRegex.test(<span class="hljs-number">2348033333333</span>)); <span class="hljs-comment">// output: true</span>
</code></pre>
<p>The reason why it worked with the <code>match()</code> method and didn’t work with <code>test()</code> is this:</p>
<ul>
<li><p>when you use the <code>match()</code> method, you can directly pass the regular expression string that you read from a JSON file as an argument to the method, and JavaScript will automatically create a regular expression from the string.</p>
</li>
<li><p>when you use the <code>test()</code> method, you need to manually create a regular expression from the regular expression string using the <code>new RegExp()</code> constructor. This is because the <code>test()</code> method expects a regular expression object as its argument, not a string.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You’ve seen that there’s no extra caveat involved in writing regular expressions in a JSON file – you still have to follow the same rules for writing JSON.</p>
<p>And when you import that JSON file into a JavaScript file, you don’t need to do anything extra to make it work, other than creating a regex out of it with the <code>new RegExp()</code> constructor in some cases.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Pretty Print JSON in Python ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide JSON (JavaScript Object Notation) is a popular data interchange format that is widely used in web applications, APIs, and databases. It is a lightweight and human-readable format that is easy to parse and generate.  But when dealing... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-pretty-print-json-in-python/</link>
                <guid isPermaLink="false">66d4610937bd2215d1e245d5</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 14 Apr 2023 15:38:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/Shittu-Olumide-How-to-Pretty-Print-JSON-in-Python.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>JSON (JavaScript Object Notation) is a popular data interchange format that is widely used in web applications, APIs, and databases. It is a lightweight and human-readable format that is easy to parse and generate. </p>
<p>But when dealing with large and complex JSON data, it can be difficult to read and understand the structure of the data. This is where pretty printing comes in. Pretty printing is the process of formatting the JSON data in a way that makes it easier to read and understand. </p>
<p>In this article, we will explore how to pretty print JSON in Python using built-in and third-party libraries. We will also cover best practices used to pretty print JSON, and also talk about it's use cases.</p>
<h2 id="heading-what-does-pretty-print-mean">What Does Pretty Print Mean?</h2>
<p>In Python, "pretty print" refers to formatting and presenting data structures such as lists, dictionaries, and tuples in a more readable and organized way. </p>
<p>To pretty print JSON in Python, we can use the built-in <code>json</code> module. This module provides a <code>dumps()</code> function that can serialize Python objects into a JSON formatted string. </p>
<p>By default, this function produces a JSON string without any formatting, but we can use the <code>indent</code> parameter to specify the number of spaces to use for indentation.</p>
<p>Here's an example of how to pretty print JSON in Python:</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> json

<span class="hljs-comment"># Sample JSON data</span>
data = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}

<span class="hljs-comment"># Convert the data to a JSON formatted string with 4 spaces of indentation</span>
json_str = json.dumps(data, indent=<span class="hljs-number">4</span>)

<span class="hljs-comment"># Print the pretty-printed JSON string</span>
print(json_str)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: 30,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}
</code></pre>
<p>As you can see, the <code>indent</code> parameter is set to <code>4</code>, which produces a JSON string with each level of nesting indented by four spaces. We can adjust this parameter to control the amount of indentation in the output.</p>
<p>Note that the <code>json.dumps()</code> function can also take other optional parameters, such as <code>sort_keys</code>, which can be used to sort the keys in the JSON output. For more information, see the documentation for the json module.</p>
<h2 id="heading-best-practices-for-pretty-print-json">Best Practices for Pretty Print JSON</h2>
<h3 id="heading-use-the-json-module">Use the <code>json</code> module</h3>
<p>The <code>json</code> module is a built-in module in Python, which provides methods for working with JSON data. The <code>json.dumps()</code> method is used to serialize Python objects into a JSON formatted string. The <code>json.dumps()</code> method also has an optional <code>indent</code> parameter that can be used to specify the number of spaces to use for indentation. </p>
<p>Here's an example:</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> json

data = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}

json_str = json.dumps(data, indent=<span class="hljs-number">4</span>)
print(json_str)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: 30,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}
</code></pre>
<h3 id="heading-use-the-pprint-module">Use the <code>pprint</code> module</h3>
<p>The <code>pprint</code> module is a built-in module in Python that provides a way to pretty print Python data structures. It also works with JSON data. The <code>pprint.pprint()</code> method is used to pretty print JSON data. </p>
<p>Here's an example:</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> pprint

data = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}

pprint.pprint(data)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{<span class="hljs-string">'age'</span>: 30, <span class="hljs-string">'city'</span>: <span class="hljs-string">'New York'</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'John'</span>}
</code></pre>
<h3 id="heading-use-third-party-libraries">Use third-party libraries</h3>
<p>There are many third-party libraries available in Python for pretty printing JSON data, such as <code>simplejson</code>, <code>ujson</code>, and <code>json5</code>. These libraries provide additional features such as faster serialization and deserialization, support for additional data types, and more flexible formatting options. </p>
<p>Here's an example using <code>simplejson</code>:</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> simplejson <span class="hljs-keyword">as</span> json

data = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">30</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>
}

json_str = json.dumps(data, indent=<span class="hljs-number">4</span>, sort_keys=<span class="hljs-literal">True</span>)
print(json_str)
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">{
    <span class="hljs-string">"age"</span>: 30,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"New York"</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John"</span>
}
</code></pre>
<h2 id="heading-pretty-print-json-in-python-use-cases">Pretty Print JSON in Python Use Cases</h2>
<ol>
<li><strong>Debugging JSON data</strong>: When working with JSON data, it can be challenging to read and understand the structure of the data if it is not well-formatted. Pretty printing JSON data in Python can help us to quickly identify any issues with the data and debug our code more efficiently.</li>
<li><strong>Displaying JSON data in user interfaces</strong>: If we are building a web application or a mobile app that displays JSON data to the user, pretty printing can enhance the user experience by making the data more readable and presentable.</li>
<li><strong>Sharing JSON data with team members</strong>: If we are working on a project with other team members and need to share JSON data with them, pretty printing the data can make it easier for them to understand the data and work with it.</li>
<li><strong>Logging JSON data</strong>: If we are logging JSON data in our Python application, pretty printing the data can make it easier to read and analyze the logs.</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Pretty printing JSON in Python is an important skill to have for anyone working with JSON data. </p>
<p>In this tutorial, we learned how to use the <code>json</code> module in Python to pretty print JSON as well as the <code>pprint</code> module. With just a few lines of code, we can generate well-formatted JSON output that is easy to read and navigate. </p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JSONObject.toString() – How to Convert JSON to a String in Java ]]>
                </title>
                <description>
                    <![CDATA[ By Shittu Olumide In the world of web applications and services, JSON (JavaScript Object Notation) has become a widely used data format for data exchange between different systems.  In Java, it's common to work with JSON data, and an operation you'll... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/jsonobject-tostring-how-to-convert-json-to-a-string-in-java/</link>
                <guid isPermaLink="false">66d461153bc3ab877dae2236</guid>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 14 Apr 2023 15:05:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/Shittu-Olumide-JSONObject.toString-----How-to-Convert-JSON-to-a-String-in-Java.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shittu Olumide</p>
<p>In the world of web applications and services, JSON (JavaScript Object Notation) has become a widely used data format for data exchange between different systems. </p>
<p>In Java, it's common to work with JSON data, and an operation you'll frequently perform is converting a JSON object to a string representation. </p>
<p>The <code>JSONObject.toString()</code> method is a powerful tool that Java developers can use to convert JSON objects to strings. </p>
<p>In this article, we will explore how to use <code>JSONObject.toString()</code> method to convert JSON objects to strings in Java. We will also discuss the benefits of using this method, and provide examples of how to use it in practical applications.</p>
<h2 id="heading-what-is-the-jsonobjecttostring-method">What is the <code>JSONObject.toString()</code> Method?</h2>
<p>JSON (JavaScript Object Notation) is a lightweight data interchange format that is widely used in web applications. It is easy to read and write, and it can be used to represent complex data structures in a simple and compact format. </p>
<p>In Java, the <code>JSONObject</code> class provided by the <code>org.json</code> package is commonly used to create and manipulate JSON objects. The <code>JSONObject.toString()</code> method is a useful method provided by this class that converts a JSON object to a string representation.</p>
<p>The <code>JSONObject.toString()</code> method takes no arguments and returns a string representation of the JSON object. This string representation is formatted according to the JSON syntax and can be used to transmit the JSON object over a network, store it in a file, or display it on a web page.</p>
<p>Here is the syntax for the <code>JSONObject.toString()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span></span>
</code></pre>
<p>To use the <code>JSONObject.toString()</code> method, you first need to create a JSON object using the <code>JSONObject</code> constructor or by parsing a JSON string using the <code>JSONObject</code> static method <code>JSONObject.parse()</code>.</p>
<p>Here is an example that demonstrates how to use the <code>JSONObject.toString()</code> method:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.json.JSONObject;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">JSONToStringExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        JSONObject jsonObject = <span class="hljs-keyword">new</span> JSONObject();
        jsonObject.put(<span class="hljs-string">"name"</span>, <span class="hljs-string">"John"</span>);
        jsonObject.put(<span class="hljs-string">"age"</span>, <span class="hljs-number">30</span>);
        jsonObject.put(<span class="hljs-string">"married"</span>, <span class="hljs-keyword">true</span>);

        String jsonString = jsonObject.toString();

        System.out.println(jsonString);
    }
}
</code></pre>
<p>In the above example, we first create a <code>JSONObject</code> instance and add some key-value pairs to it using the <code>put()</code> method. Then, we call the <code>toString()</code> method on the <code>JSONObject</code> instance to get a string representation of the JSON object. Finally, we print the string to the console.</p>
<p>The output of the above code would be:</p>
<pre><code class="lang-bash">{<span class="hljs-string">"name"</span>:<span class="hljs-string">"John"</span>,<span class="hljs-string">"age"</span>:30,<span class="hljs-string">"married"</span>:<span class="hljs-literal">true</span>}
</code></pre>
<p>As you can see, the <code>JSONObject.toString()</code> method has converted the JSON object to a string representation that conforms to the JSON syntax. The string representation includes the key-value pairs and the appropriate punctuation marks (braces, commas, and colons) to represent the structure of the JSON object.</p>
<h2 id="heading-benefits-of-using-the-jsonobjecttostring-method">Benefits of using the <code>JSONObject.toString()</code> method</h2>
<ol>
<li><strong>Easy Serialization</strong>: Using the <code>JSONObject.toString()</code> method makes it easy to serialize a <code>JSONObject</code> to a JSON-formatted string, which can then be transmitted over a network or stored in a file. This string representation can also be easily deserialized back into a <code>JSONObject</code> or other JSON-compatible object in the future.</li>
<li><strong>Debugging</strong>: When debugging an application that uses JSON data, it can be helpful to log the JSON string representation of the <code>JSONObject</code> instance. This can help to diagnose issues related to JSON data processing.</li>
<li><strong>Readability</strong>: The JSON format is a lightweight and easy-to-read format for storing and exchanging data. By using the <code>JSONObject.toString()</code> method, you can generate a JSON-formatted string that is easy to read and understand by other developers or systems.</li>
<li><strong>Cross-platform compatibility</strong>: JSON is a widely-used data format that is supported by many programming languages and platforms. By using the <code>JSONObject.toString()</code> method, you can easily generate a JSON-formatted string that can be consumed by other systems or services regardless of the programming language or platform they are using.</li>
<li><strong>Flexibility</strong>: The <code>JSONObject.toString()</code> method can be used to generate JSON-formatted strings that can represent complex and nested data structures. This flexibility allows you to represent a wide range of data types and structures in a standardized format that can be easily consumed by other systems or services.</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>JSONObject.toString()</code> method is a useful method provided by the <code>org.json</code> package in Java that converts a JSON object to a string representation. This method is essential when transmitting JSON data over a network, storing it in a file, or displaying it on a web page. </p>
<p>By following the syntax and examples outlined in this article, you can use the <code>JSONObject.toString()</code> method to easily convert JSON objects to string representations in your Java programs.</p>
<p>Let's connect on <a target="_blank" href="https://www.twitter.com/Shittu_Olumide_">Twitter</a> and on <a target="_blank" href="https://www.linkedin.com/in/olumide-shittu">LinkedIn</a>. You can also subscribe to my <a target="_blank" href="https://www.youtube.com/channel/UCNhFxpk6hGt5uMCKXq0Jl8A">YouTube</a> channel.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Comments Inside JSON – Commenting in a JSON File ]]>
                </title>
                <description>
                    <![CDATA[ JSON (JavaScript Object Notation) is a popular data interchange format used in web development and mobile applications due to its simplicity and flexibility. But JSON files do not officially support comments. This makes providing additional context o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/comments-in-json/</link>
                <guid isPermaLink="false">66d45f6f9f2bec37e2da0624</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Fri, 31 Mar 2023 15:10:51 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/cover-template--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JSON (JavaScript Object Notation) is a popular data interchange format used in web development and mobile applications due to its simplicity and flexibility.</p>
<p>But JSON files do not officially support comments. This makes providing additional context or explanation for the data challenging.</p>
<p>This article will show you how to include comments in JSON files and why JSON does not natively support comments.</p>
<h2 id="heading-why-json-does-not-support-comments">Why JSON Does Not Support Comments?</h2>
<p>According to the JSON specification, a JSON document should only contain data structures like arrays and objects and not include comments. This is because JSON is intended to be a simple, easily parsable data format that can be quickly and efficiently processed.</p>
<p>Comments, while useful for providing additional context or explanation for human readers, can add complexity to the parsing process. This slows down performance and increases the risk of errors.</p>
<p>The primary reason why JSON does not support comments is that its creator, <a target="_blank" href="https://en.wikipedia.org/wiki/Douglas_Crockford">Douglas Crockford</a>, deliberately removed them from the format to prevent misuse and keep it as a pure data-only format.</p>
<p>Crockford observed that some people were using comments to store parsing directives, which could break compatibility between different systems. Hence, the decision to remove comments to maintain the simplicity and consistency of the format across various programming languages and environments.</p>
<p>As a result, the only option for adding comments to a JSON file is to use a workaround, such as using custom elements to store comments.</p>
<h2 id="heading-how-to-add-comments-inside-json">How to Add Comments Inside JSON</h2>
<p>When you add comments in the form <code>//</code>, <code>#</code>, or <code>/* */</code>, which are used in popular programming languages, you will notice the error “Comments are not permitted in JSON”.</p>
<p><img src="https://paper-attachments.dropboxusercontent.com/s_7788E690364D593F2C3E31F8D1CF26EB90DAC0141414EE29BD5F57C061BD4347_1680020901125_image.png" alt="s_7788E690364D593F2C3E31F8D1CF26EB90DAC0141414EE29BD5F57C061BD4347_1680020901125_image" width="1774" height="354" loading="lazy"></p>
<p>Then, how can you add comments to a JSON file?</p>
<p>The only way this can be done is to include comments as data pairs in a JSON file. It is not a commonly used or recommended practice, but technically it’s the best way to add comments to your JSON file.</p>
<p>Create a custom element within your JSON object, such as "_comment", to distinguish them from the rest of the data.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"Put your JSON comment here"</span>
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"occupation"</span>: <span class="hljs-string">"Software Engineer"</span>,
}
</code></pre>
<p><strong>Note:</strong> It's not compulsory that you use underscores. You can decide to use two slash such as “//comment” or any other allowed character. <strong>The goal is to make it clear that it’s a comment</strong>.</p>
<p>It's important to note that this approach may make the JSON file more complex and harder to parse. But if comments are added as custom elements, they will be received and processed like any other data in JSON on the server-side.</p>
<p>You now know how to add comments to your JSON file technically. But how can you add multiple comments? This is possible, but you should remember that JSON does not allow duplicate object keys. You must include unique letters or numbers in the comment element, ensuring it is valid and distinguishable from other elements in the JSON file.</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment1"</span>: <span class="hljs-string">"This is the basic data"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"_comment2"</span>: <span class="hljs-string">"Marital information"</span>,
    <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"wifeName"</span>: <span class="hljs-string">"Jane Doe"</span>
}
</code></pre>
<p>When you have nested JSON objects, you can use similar object keys:</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"This is the basic data"</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">35</span>,
    <span class="hljs-attr">"city"</span>: <span class="hljs-string">"New York City"</span>,
    <span class="hljs-attr">"maritalInfo"</span>: {
        <span class="hljs-attr">"_comment"</span>: <span class="hljs-string">"Marital information"</span>,
        <span class="hljs-attr">"isMarried"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-attr">"wifeName"</span>: <span class="hljs-string">"Jane Doe"</span>
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You now know how to add comments to your JSON file. But because these comments are also processed and can be accessed, you need to be careful when adding comments to JSON files using custom elements.</p>
<p>Thanks for reading. Have fun coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Read a JSON File in JavaScript – Reading JSON in JS ]]>
                </title>
                <description>
                    <![CDATA[ When fetching data from external sources or servers, you need to make sure that the data returned is in JSON format. Then you can consume the data within your application. In some situations, when you're working locally or when you upload the data fi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-read-json-file-in-javascript/</link>
                <guid isPermaLink="false">66d45fad4bc8f441cb6df80b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joel Olawanle ]]>
                </dc:creator>
                <pubDate>Tue, 02 Aug 2022 21:35:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/08/cover-template--5-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When fetching data from external sources or servers, you need to make sure that the data returned is in JSON format. Then you can consume the data within your application.</p>
<p>In some situations, when you're working locally or when you upload the data file to a server, we might want to read these JSON data from a file.</p>
<p>We'll learn how to do that in this tutorial.</p>
<h2 id="heading-how-to-read-a-json-file-in-javascript-with-the-fetch-api">How to Read a JSON File in JavaScript with the Fetch API</h2>
<p>One standard method we can use to read a JSON file (either a local file or one uploaded to a server) is with the Fetch API. It uses the same syntax for both. The only difference would be the URL.</p>
<p>For example, suppose we have a local file within our project's folder named <code>data.json</code> that contains the following JSON data:</p>
<pre><code class="lang-json">&lt;!--./data.JSON--&gt;

{
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Hello World"</span>,
    <span class="hljs-attr">"completed"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>We can now read this file in JavaScript using the Fetch API method:</p>
<pre><code class="lang-js">&lt;!--./index.js--&gt;

fetch(<span class="hljs-string">'./data.json'</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(json));
</code></pre>
<p>In the above, we have been able to read a local JSON file. But unfortunately, when we run this in a browser, we might get the following CORS error because our file is not on a server:</p>
<p><img src="https://paper-attachments.dropbox.com/s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image.png" alt="s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image" width="600" height="400" loading="lazy"></p>
<p>To fix this, we will make sure our JSON file is on a local or remote server. If we use the Live server on our IDE, we won't get this error. But when we load our file directly, we will get this error.</p>
<p>As I said earlier, suppose we have this JSON file on a remote server and are trying to read this file in JavaScript. The same syntax will work:</p>
<pre><code class="lang-js">&lt;!--./index.js--&gt;

fetch(<span class="hljs-string">'https://server.com/data.json'</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> response.json())
    .then(<span class="hljs-function">(<span class="hljs-params">json</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(json));
</code></pre>
<p>The fetch API is the preferable method to use when we want to read a JSON file either from an external server or local file into our JavaScript file.</p>
<h2 id="heading-how-to-read-a-json-file-in-javascript-with-the-import-statement">How to Read a JSON file in JavaScript with the Import Statement</h2>
<p>Another method we can use aside from making an HTTP request is the import statement. This method has a few complications, but we will address them all.</p>
<p>Just like in the previous section, suppose we have our JSON file that holds user data, such as <code>user.json</code>:</p>
<pre><code class="lang-json">&lt;!--./user.JSON--&gt;

{
    <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"age"</span>: <span class="hljs-number">12</span>
}
</code></pre>
<p>We can read this JSON data in JavaScript using the import statement this way:</p>
<pre><code class="lang-js">&lt;!---./index.js--&gt;

<span class="hljs-keyword">import</span> data <span class="hljs-keyword">from</span> <span class="hljs-string">'./data.json'</span>;
<span class="hljs-built_in">console</span>.log(data);
</code></pre>
<p>Unfortunately, this will throw an error saying we cannot use the import statement outside a module. This is a standard error when we try to use the <code>import</code> statement in a regular JavaScript file, especially for developers who are new to JavaScript.</p>
<p>To fix this, we can add the <code>type="module"</code> script tag in our HTML file where we referenced the JavaScript file, like this:</p>
<pre><code class="lang-HTML"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
    // ...
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>When we do this, we'll still get another error:</p>
<p><img src="https://paper-attachments.dropbox.com/s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659465574774_image.png" alt="s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659465574774_image" width="600" height="400" loading="lazy"></p>
<p>To fix this error, we need to add the file type of JSON to the import statement, and then we'll be able to read our JSON file in JavaScript:</p>
<pre><code class="lang-bash">import data from <span class="hljs-string">'./data.json'</span> assert { <span class="hljs-built_in">type</span>: <span class="hljs-string">'json'</span> };
console.log(data);
</code></pre>
<p>This works perfectly as long as we run our files on a local or remote server. But suppose we run this locally – then we would get the CORS error.</p>
<p><img src="https://paper-attachments.dropbox.com/s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image.png" alt="s_9630F87AB23B79DCD31DCDD0E14D2C6C4A3007934D2E561803A41CF5C1FE0085_1659464623693_image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, we have learned how to read a JSON file in JavaScript and the possible errors we might encounter when using each method.</p>
<p>It's best to use the fetch API method when you want to make an HTTP request. For example, suppose we are fetching data from a mock JSON file which we will eventually pull from an API.</p>
<p>Still, in a situation where we don't need to use an HTTP request, we could use the import statement. We can use the import statement when we use a library like React, Vue, and so on which has to do with modules. This means we won't need to add the type of module, and also, we won't need to add the type of file.</p>
<p>Neither method requires you to install a package or use a library as they are inbuilt. Choosing which method to use is totally up to you.</p>
<p>But a quick tip that differentiates these methods is that the Fetch API reads a JSON file in JavaScript by sending an HTTP request, while the import statement does not require any HTTP request but rather works like every other import we make.</p>
<p>Embark on a journey of learning! <a target="_blank" href="https://joelolawanle.com/contents">Browse 200+ expert articles on web development</a>. Check out <a target="_blank" href="https://joelolawanle.com/posts">my blog</a> for more captivating content from me.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Loading a JSON File in Python – How to Read and Parse JSON ]]>
                </title>
                <description>
                    <![CDATA[ By Dillion Megida In this article, you'll learn how to read and parse JSON in Python. What is JSON? JSON is short for JavaScript Object Notation. It's a simple syntax for storing data in name-value pairs. Values can be different data types as long as... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/loading-a-json-file-in-python-how-to-read-and-parse-json/</link>
                <guid isPermaLink="false">66d84f404c5150361c4fdb22</guid>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 25 Jul 2022 14:06:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/read-parse-json-files.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dillion Megida</p>
<p>In this article, you'll learn how to read and parse JSON in Python.</p>
<h2 id="heading-what-is-json">What is JSON?</h2>
<p>JSON is short for JavaScript Object Notation. It's a simple syntax for storing data in name-value pairs. Values can be different data types as long as they are valid. Non-acceptable types for JSON include functions, dates, and <code>undefined</code>.</p>
<p>JSON files are stored with the <code>.json</code> extension with a valid JSON structure.</p>
<p>Here's what the structure of a JSON file looks like:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"John"</span>,
  <span class="hljs-attr">"age"</span>: <span class="hljs-number">50</span>,
  <span class="hljs-attr">"is_married"</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">"profession"</span>: <span class="hljs-literal">null</span>,
  <span class="hljs-attr">"hobbies"</span>: [<span class="hljs-string">"traveling"</span>, <span class="hljs-string">"photography"</span>]
}
</code></pre>
<p>You'll often use JSON to send and receive data from a server in web applications.</p>
<p>When the data is received, the program reads and parses the JSON to extract specific data. Different languages have their own methods for doing this. We'll look at how to do these in Python here.</p>
<h2 id="heading-how-to-read-json-files">How to Read JSON Files</h2>
<p>Let's say the JSON in the code block above is stored in a <code>user.json</code> file. Using the <code>open()</code> inbuilt function in Python, we can read that file and assign the content to a variable. Here's how:</p>
<pre><code class="lang-python"><span class="hljs-keyword">with</span> open(<span class="hljs-string">'user.json'</span>) <span class="hljs-keyword">as</span> user_file:
  file_contents = user_file.read()

print(file_contents)
<span class="hljs-comment"># {</span>
<span class="hljs-comment">#   "name": "John",</span>
<span class="hljs-comment">#   "age": 50,</span>
<span class="hljs-comment">#   "is_married": false,</span>
<span class="hljs-comment">#   "profession": null,</span>
<span class="hljs-comment">#   "hobbies": ["travelling", "photography"]</span>
<span class="hljs-comment"># }</span>
</code></pre>
<p>You pass the file path to the <code>open</code> method which opens the file and assigns the stream data from the file to the <code>user_file</code> variable. Using the <code>read</code> method, you can pass the text contents of the file to the <code>file_contents</code> variable.</p>
<p>I used <code>with</code> at the beginning of the expression so that after reading the contents of the file, Python can close the file.</p>
<p><code>file_contents</code> now contains a stringified version of the JSON. As a next step, you can now parse the JSON.</p>
<h2 id="heading-how-to-parse-json">How to Parse JSON</h2>
<p>Python has in-built modules for various operations. For managing JSON files, Python has the <code>json</code> module.</p>
<p>This module comes with many methods. One of which is the <code>loads()</code> method for parsing JSON strings. Then, you can assign the parsed data to a variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> json

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'user.json'</span>) <span class="hljs-keyword">as</span> user_file:
  file_contents = user_file.read()

print(file_contents)

parsed_json = json.loads(file_contents)
# {
#   <span class="hljs-string">'name'</span>: <span class="hljs-string">'John'</span>,
#   <span class="hljs-string">'age'</span>: <span class="hljs-number">50</span>,
#   <span class="hljs-string">'is_married'</span>: False,
#   <span class="hljs-string">'profession'</span>: None,
#   <span class="hljs-string">'hobbies'</span>: [<span class="hljs-string">'travelling'</span>, <span class="hljs-string">'photography'</span>]
# }
</code></pre>
<p>Using the <code>loads()</code> method, you can see that the <code>parsed_json</code> variable now has a valid dictionary. From this dictionary, you can access the keys and values in it.</p>
<p>Also notice how <code>null</code> from the JSON is converted to <code>None</code> in python. This is because <code>null</code> is not valid in <code>Python</code>.</p>
<h2 id="heading-how-to-use-jsonload-to-read-and-parse-json-files">How to Use <code>json.load()</code> to Read and Parse JSON Files</h2>
<p>The <code>json</code> module also has the <code>load</code> method which you can use to read a file object and parse it at the same time. Using this method, you can update the previous code to this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> json

<span class="hljs-keyword">with</span> open(<span class="hljs-string">'user.json'</span>) <span class="hljs-keyword">as</span> user_file:
  parsed_json = json.load(user_file)

print(parsed_json)
<span class="hljs-comment"># {</span>
<span class="hljs-comment">#   'name': 'John',</span>
<span class="hljs-comment">#   'age': 50,</span>
<span class="hljs-comment">#   'is_married': False,</span>
<span class="hljs-comment">#   'profession': None,</span>
<span class="hljs-comment">#   'hobbies': ['travelling', 'photography']</span>
<span class="hljs-comment"># }</span>
</code></pre>
<p>Instead of using the <code>read</code> method of the file object and using the <code>loads</code> method of the <code>json</code> module, you can directly use the <code>load</code> method which reads and parses the file object.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>JSON data is commonly known for its simple structure and is popular (a standard in most cases) for information exchange between servers and clients.</p>
<p>Different languages and technologies can read and parse JSON files in different ways. In this article, we've learned how to read JSON files and parse such files using the <code>read</code> method of file objects, and the <code>loads</code> and <code>load</code> methods of the <code>json</code> module.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
