{"id":208,"date":"2026-08-09T07:47:32","date_gmt":"2026-08-09T07:47:32","guid":{"rendered":"https:\/\/blog.csfree.org\/?p=208"},"modified":"2026-08-09T07:47:32","modified_gmt":"2026-08-09T07:47:32","slug":"an-introduction-to-json-how-web-apps-exchange-data","status":"publish","type":"post","link":"https:\/\/blog.csfree.org\/index.php\/2026\/08\/09\/an-introduction-to-json-how-web-apps-exchange-data\/","title":{"rendered":"An Introduction to JSON: How Web Apps Exchange Data"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">An Introduction to JSON: How Web Apps Exchange Data<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Building a web application today is like assembling an international team- the user interface, backend server, database, and third-party services often speak completely different native languages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Similarly, your frontend might be a single-page app built with <strong>React<\/strong> running inside a browser\u2019s JavaScript engine. Your backend API might be powered by <strong>Python and Flask <\/strong>or <strong>Django<\/strong>, while a microservice next door runs on <strong>Go<\/strong> or <strong>Java<\/strong>, connected to a <strong>PostgreSQL<\/strong> database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Despite operating on fundamentally distinct programming paradigms, these isolated environments must constantly share information, whether it\u2019s authenticating a login attempt, displaying a user profile, or updating a shopping cart in real time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To understand why we need a format like JSON, we first have to understand how programming languages handle data in memory:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Language-Speceific Incompatibility<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In-memory data structures are exclusive to their host language.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>JavaScript stores structured data as <strong>Objects<\/strong> and <strong>Maps<\/strong>.<\/li>\n\n\n\n<li>Python stores structured data as <strong>Dictionaries<\/strong> (<code>dict<\/code>).<\/li>\n\n\n\n<li>Java uses <strong>HashMaps<\/strong> or class instances.<\/li>\n\n\n\n<li>C++ uses <strong>structs<\/strong> or standard library containers.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">A <strong>Python backend <\/strong>cannot directly stream its in-memory dictionary data to a J<strong>avaScript browser<\/strong>. <strong>JavaScript<\/strong> has no native understanding of <strong>Python&#8217;s<\/strong> memory layout or binary representations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So, how would they interact?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Computer networks (routers, switches, and standard HTTP servers) do not understand complex code structures or objects. Networks transmit raw <strong>bytes and text<\/strong>. For data to travel over the wire, it must be flattened down into a continuous text stream, a process known as <strong>serialization<\/strong>. Without a universal standard, every developer pairing (e.g., Python-to-JavaScript, Java-to-Swift) would have to write custom binary conversion protocols just to pass a simple payload like <code>username<\/code> and <code>email<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h4 class=\"wp-block-heading\">The Solution: A Universal Data Format<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">To bridge this gap, web architectures rely on a single, language-based intermediate format. The requirements for this format are simple:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Universal Parsing:<\/strong> Any language must be able to convert its native data into this format (serialize) and convert this format back into its native data (deserialize).<\/li>\n\n\n\n<li><strong>Text-Based:<\/strong> Easily sent over standard network protocols (like HTTP\/HTTPS) without getting corrupted by system-level differences (such as big-endian vs. little-endian architecture).<\/li>\n\n\n\n<li><strong>Human-Readable:<\/strong> Developers must be able to open network tools, read the data, and debug requests easily without needing specialized binary decoders.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This is precisely where <strong>JSON<\/strong> steps in, acting as the common ground that allows entirely different tech stacks to communicate seamlessly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is JSON?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <strong>JSON file<\/strong> is a lightweight, plain-text document used to store and organize structured data. It uses the <code>.json<\/code> file extension and follows the <strong>JavaScript Object Notation<\/strong> standard.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">At its core, a <strong>JSON file<\/strong> is just a standard text file (like <code>.txt<\/code>). You can open, read, and edit it with any basic text editor (VS Code, Notepad, Vim). <\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>File extension:<\/strong> <code>.json<\/code> (e.g., <code>user_config.json<\/code>, <code>data.json<\/code>) and <strong>MIME type:<\/strong> <code>application\/json<\/code> (used in network headers). By default, <strong>JSON files<\/strong> are also encoded in UTF-8, allowing them to support multi-language characters and international data smoothly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Inside a <code><strong>.json<\/strong><\/code> file, data is written using two fundamental structures:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Key\/Value Pairs (Objects):<\/strong> Wrapped in curly braces <code>{}<\/code>. Keys are always strings, followed by a colon <code>':<\/code>&#8216;, and then the value.<\/li>\n\n\n\n<li><strong>Ordered Lists (Arrays):<\/strong> Wrapped in square brackets <code>[]<\/code>. Values are separated by commas &#8216;<code>,<\/code>&#8216;.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example of a <code>.json<\/code> File (<code>settings.json<\/code>)<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>{\n  \"appName\": \"DevTracker\",\n  \"version\": 2.1,\n  \"isDarkModeEnabled\": true,\n  \"maxProjectsAllowed\": 10,\n  \"supportedLanguages\": &#91;\"JavaScript\", \"Python\", \"Go\"],\n  \"owner\": {\n    \"name\": \"Alex\",\n    \"email\": \"alex@example.com\"\n  },\n  \"backupSchedule\": null\n}<\/strong><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">What are the data-types allowed in a JSON file?<\/h4>\n\n\n\n<figure class=\"wp-block-table aligncenter\"><table class=\"has-fixed-layout\"><thead><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Data Type<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Description<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Example<\/strong><\/td><\/tr><\/thead><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>String<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">Text wrapped in double quotes <code>\"\"<\/code><\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>\"Hello\"<\/code><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Number<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">Integer or floating-point number<\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>42<\/code> or <code>99.99<\/code><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Boolean<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">Logical true or false<\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>true<\/code> or <code>false<\/code><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Array<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">An ordered list of values<\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>[\"a\", \"b\", \"c\"]<\/code><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Object<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">A collection of key\/value pairs<\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>{\"key\": \"value\"}<\/code><\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\"><strong>Null<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">Represents an empty or nonexistent value<\/td><td class=\"has-text-align-center\" data-align=\"center\"><code>null<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note: <\/strong>Functions\/code, executable logic, comments (<code>\/\/<\/code> or <code>\/* *\/<\/code>), single quotes (<code>'<\/code>), or trailing commas after the last element are not allowed inside a <strong>JSON file<\/strong>. but, <strong>JSONC (JSON with Comments):<\/strong> Supported by VS Code (<code>settings.json<\/code>) and TypeScript config (<code>tsconfig.json<\/code>). Allows <code>\/\/<\/code> and <code>\/* *\/<\/code> comments and <strong>JSON5:<\/strong> Expanded syntax that allows single quotes, trailing commas, multi-line strings, hex numbers, and unquoted keys for human-written config files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key Uses of JSON Files:<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">JSON files serve three major roles in modern computing:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">A. Application Configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Many frameworks, tools, and environments use <code>.json<\/code> files to manage project settings because they are easy for both humans and scripts to read.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><code>package.json<\/code><\/strong> in Node.js (manages dependencies and scripts).<\/li>\n\n\n\n<li><strong><code>tsconfig.json<\/code><\/strong> in TypeScript (defines compiler settings).<\/li>\n\n\n\n<li><strong><code>settings.json<\/code><\/strong> in editors like VS Code (stores user preferences).<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">B. Static Data Storage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Small datasets, seed data for databases, mock data for local testing, or internationalization (i18n) translation files are often saved as local <code>.json<\/code> files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">C. Offline Data Transfer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">When APIs need to export bulk data (e.g., downloading your profile data from a web service), they frequently package and export it as a downloadable <code>.json<\/code> file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Following snippets is how to read and write local <code>.json<\/code> files in various languages-<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Python (<code>json<\/code> module)<\/strong>: <strong>Python <\/strong>comes with a built-in <code>json<\/code> package. It uses <code>json.load()<\/code> to read from a file and <code>json.dump()<\/code> to write to a file.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing to a JSON File (<code>write_example.py<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>import json\n\n# Python dictionary to save\ndata = {\n    \"appName\": \"DevTracker\",\n    \"version\": 2.1,\n    \"isDarkModeEnabled\": True,  # Automatically converts to true in JSON\n    \"supportedLanguages\": &#91;\"JavaScript\", \"Python\", \"Go\"],\n    \"owner\": {\n        \"name\": \"Alex\",\n        \"email\": \"alex@example.com\"\n    }\n}\n\n# Write dictionary to data.json\n# indent=4 formats the output with clean spacing (pretty-printing)\nwith open(\"data.json\", \"w\", encoding=\"utf-8\") as file:\n    json.dump(data, file, indent=4)\n\nprint(\"data.json created successfully!\")<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Reading from a JSON File (<code>read_example.py<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>import json\n\n# Read data.json into a Python dictionary\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    loaded_data = json.load(file)\n\n# Accessing values like a standard dictionary\nprint(\"App Name:\", loaded_data&#91;\"appName\"])\nprint(\"First Language:\", loaded_data&#91;\"supportedLanguages\"]&#91;0])\nprint(\"Owner Email:\", loaded_data&#91;\"owner\"]&#91;\"email\"])<\/strong><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>JavaScript (Node.js <code>fs<\/code> module)<\/strong>: In Node.js, you can use the built-in <code>fs<\/code> (File System) module with <code>fs.promises<\/code> or <code>fs.readFileSync<\/code> \/ <code>fs.writeFileSync<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing to a JSON File (<code>write_example.js<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>const fs = require('fs\/promises');\n\n\/\/ JavaScript Object to save\nconst data = {\n  appName: \"DevTracker\",\n  version: 2.1,\n  isDarkModeEnabled: true,\n  supportedLanguages: &#91;\"JavaScript\", \"Python\", \"Go\"],\n  owner: {\n    name: \"Alex\",\n    email: \"alex@example.com\"\n  }\n};\n\nasync function writeJsonFile() {\n  try {\n    \/\/ 1. Convert JS Object to JSON String\n    \/\/ null, 2 formats the file with 2 spaces of indentation\n    const jsonString = JSON.stringify(data, null, 2);\n\n    \/\/ 2. Write string to file\n    await fs.writeFile('data.json', jsonString, 'utf-8');\n    console.log('data.json created successfully!');\n  } catch (error) {\n    console.error('Error writing file:', error);\n  }\n}\n\nwriteJsonFile();<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Reading from a JSON File (<code>read_example.js<\/code>), using <code>fs.promises<\/code> (Recommended for general data files)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>const fs = require('fs\/promises');\n\nasync function readJsonFile() {\n  try {\n    \/\/ 1. Read raw file contents as string\n    const rawData = await fs.readFile('data.json', 'utf-8');\n\n    \/\/ 2. Parse JSON String into a JavaScript Object\n    const loadedData = JSON.parse(rawData);\n\n    \/\/ Access values\n    console.log(\"App Name:\", loadedData.appName);\n    console.log(\"First Language:\", loadedData.supportedLanguages&#91;0]);\n    console.log(\"Owner Email:\", loadedData.owner.email);\n  } catch (error) {\n    console.error('Error reading file:', error);\n  }\n}\n\nreadJsonFile();<\/strong><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>PHP :<\/strong> PHP handles JSON natively using built-in functions like <code>json_encode()<\/code>, <code>json_decode()<\/code>, <code>file_get_contents()<\/code>, and <code>file_put_contents()<\/code>.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing &amp; Reading Example (<code>index.php<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>&lt;?php\n$filePath = 'data.json';\n\n\/\/ 1. Prepare Data\n$data = &#91;\n    \"appName\" =&gt; \"DevTracker\",\n    \"version\" =&gt; 2.1,\n    \"supportedLanguages\" =&gt; &#91;\"PHP\", \"Python\", \"JavaScript\"]\n];\n\n\/\/ 2. WRITE to JSON file\n\/\/ JSON_PRETTY_PRINT formats the output nicely\n$jsonString = json_encode($data, JSON_PRETTY_PRINT);\nfile_put_contents($filePath, $jsonString);\necho \"File written successfully!\\n\";\n\n\/\/ 3. READ from JSON file\n$rawJson = file_get_contents($filePath);\n\n\/\/ Setting 2nd argument to true converts JSON into an associative array\n$loadedData = json_decode($rawJson, true);\n\necho \"App Name: \" . $loadedData&#91;'appName'] . \"\\n\";\necho \"First Language: \" . $loadedData&#91;'supportedLanguages']&#91;0] . \"\\n\";\n?&gt;<\/strong><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Go (Golang)<\/strong>: Go uses its standard library package <code>encoding\/json<\/code> combined with the <code>os<\/code> package.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing &amp; Reading Example (<code>main.go<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n)\n\n\/\/ Define a struct matching the JSON structure\ntype Config struct {\n\tAppName            string   `json:\"appName\"`\n\tVersion            float64  `json:\"version\"`\n\tSupportedLanguages &#91;]string `json:\"supportedLanguages\"`\n}\n\nfunc main() {\n\tfilePath := \"data.json\"\n\n\tdata := Config{\n\t\tAppName:            \"DevTracker\",\n\t\tVersion:            2.1,\n\t\tSupportedLanguages: &#91;]string{\"Go\", \"Python\", \"JavaScript\"},\n\t}\n\n\t\/\/ 1. WRITE to JSON file\n\t\/\/ MarshalIndent converts struct to formatted JSON bytes\n\tjsonBytes, _ := json.MarshalIndent(data, \"\", \"  \")\n\t_ = os.WriteFile(filePath, jsonBytes, 0644)\n\tfmt.Println(\"File written successfully!\")\n\n\t\/\/ 2. READ from JSON file\n\tfileBytes, _ := os.ReadFile(filePath)\n\tvar loadedData Config\n\n\t\/\/ Unmarshal converts JSON bytes back into Go struct\n\t_ = json.Unmarshal(fileBytes, &amp;loadedData)\n\tfmt.Println(\"App Name:\", loadedData.AppName)\n\tfmt.Println(\"First Language:\", loadedData.SupportedLanguages&#91;0])\n}<\/strong><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>C# (.NET)<\/strong>: Modern .NET includes high-performance built-in JSON support via <code>System.Text.Json<\/code>. <\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Writing &amp; Reading Example (<code>Program.cs<\/code>)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>using System;\nusing System.IO;\nusing System.Text.Json;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n        string filePath = \"data.json\";\n\n        var data = new\n        {\n            appName = \"DevTracker\",\n            version = 2.1,\n            supportedLanguages = new List&lt;string&gt; { \"C#\", \"Python\", \"JavaScript\" }\n        };\n\n        \/\/ 1. WRITE to JSON file\n        var options = new JsonSerializerOptions { WriteIndented = true };\n        string jsonString = JsonSerializer.Serialize(data, options);\n        File.WriteAllText(filePath, jsonString);\n        Console.WriteLine(\"File written successfully!\");\n\n        \/\/ 2. READ from JSON file\n        string readJsonString = File.ReadAllText(filePath);\n        using JsonDocument doc = JsonDocument.Parse(readJsonString);\n        \n        JsonElement root = doc.RootElement;\n        Console.WriteLine($\"App Name: {root.GetProperty(\"appName\").GetString()}\");\n    }\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Note: <\/strong>In dynamic languages like <strong>JavaScript <\/strong>or <strong>Python<\/strong>, parsing <strong>JSON <\/strong>feels almost invisible. A <strong>JSON <\/strong>string becomes a flexible JavaScript object or Python dictionary, allowing you to access properties on the fly without declaring what shape the data should take. However, in strongly typed enterprise languages like <strong>Go, C#<\/strong> etc, every variable must have an explicit data type defined at compile time. These languages cannot simply receive arbitrary <strong>JSON <\/strong>without knowing its structure in advance.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead, they map incoming <strong>JSON <\/strong>payloads directly to <strong>Structs<\/strong> or <strong>Classes<\/strong> through a process called <strong>Data Binding<\/strong> (or Schema Unmarshalling).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">How do backends validate incoming JSON before touching the database? <strong>JSON Schema<\/strong>.<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Accepting arbitrary <strong>JSON <\/strong>from external users or third-party APIs can be risky. If an incoming request is missing a mandatory <code>email<\/code> key or sends an age of <code>-50<\/code> as a string instead of a positive integer, your backend software might crash or pollute your database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To prevent this, applications rely on <strong>data validation schemas<\/strong>, blueprints that define the precise shape, required keys, data types, and value limits of expected <strong>JSON<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">What is JSON Schema?<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>JSON Schema<\/strong> is a vocabulary that allows you to annotate and validate JSON documents. Think of it as a strict contract or blueprint for your data structure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A JSON Schema specifies &#8211; What <strong>data types<\/strong> each value must have (<code>string<\/code>, <code>integer<\/code>, <code>boolean<\/code>, etc.), which keys <strong>must<\/strong> be present (required fields), value constraints (minimum\/maximum limits, regex string patterns, array lengths) and default fallback values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>An Example: JSON Schema<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is how you write a official standard JSON Schema blueprint to validate a user registration payload:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>{\n  \"$schema\": \"https:\/\/json-schema.org\/draft\/2020-12\/schema\",\n  \"type\": \"object\",\n  \"properties\": {\n    \"username\": {\n      \"type\": \"string\",\n      \"minLength\": 3\n    },\n    \"email\": {\n      \"type\": \"string\",\n      \"format\": \"email\"\n    },\n    \"age\": {\n      \"type\": \"integer\",\n      \"minimum\": 18,\n      \"maximum\": 120\n    }\n  },\n  \"required\": &#91;\"username\", \"email\", \"age\"],\n  \"additionalProperties\": false\n}<\/strong><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">What this Schema Enforces?<\/h4>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Required Fields:<\/strong> The JSON object <strong>must<\/strong> contain <code>username<\/code>, <code>email<\/code>, and <code>age<\/code>.<\/li>\n\n\n\n<li><strong>Email Format:<\/strong> The <code>email<\/code> field must follow a valid email string format.<\/li>\n\n\n\n<li><strong>Age Constraints:<\/strong> The <code>age<\/code> field must be an integer between <code>18<\/code> and <code>120<\/code>.<\/li>\n\n\n\n<li><strong>No Extra Keys:<\/strong> <code>\"additionalProperties\": false<\/code> rejects any unexpected fields sent by the client.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">JSON Security Pitfalls: Mass Assignment &amp; JSON Injection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Because <strong>JSON <\/strong>is plain text and easily mapped directly into application logic or database models, it introduces security vulnerabilities if handled carelessly. When receiving <strong>JSON <\/strong>from unauthenticated or untrusted users, developers must guard against two major security pitfalls: <strong>Mass Assignment<\/strong> and <strong>JSON Injection<\/strong>.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Mass Assignment (Over-Posting)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Mass Assignment occurs when a framework automatically binds an incoming JSON payload directly to an internal data model or database record without filtering which fields the user is allowed to update.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>How the Attack Works<\/strong>:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine a user updating their profile details (bio and username). The application receives this standard update request:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>{\n  \"bio\": \"Full-stack developer building cool apps.\",\n  \"location\": \"Kolkata\"\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the backend takes the entire <strong>JSON <\/strong>object and passes it straight into an ORM update query (e.g., <code>User.update(request.json)<\/code>), a malicious user can inspect the network request and inject unexpected administrative fields into the payload:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>{\n  \"bio\": \"Full-stack developer building cool apps.\",\n  \"location\": \"Kolkata\",\n  \"role\": \"admin\",\n  \"isVerified\": true,\n  \"accountBalance\": 999999\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Because the backend blindly updates all keys matching the database schema, the attacker just elevated their privilege level to administrator simply by adding <code>\"role\": \"admin\"<\/code> to their JSON payload.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Prevention<\/strong>: <strong>Never bind raw JSON directly to database models.<\/strong> Use <strong>Data Transfer Objects (DTOs)<\/strong>, explicit field whitelists, or validation schemas (like Zod or Pydantic) to strictly define allowed input fields before processing.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>JSON Injection<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">JSON Injection happens when an application constructs JSON strings by concatenating un-sanitized user input rather than using a proper native serialization function (<code>JSON.stringify()<\/code> or <code>json.dumps()<\/code>).<\/p>\n\n\n\n<h5 class=\"wp-block-heading\">How the Attack Works:<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Suppose a backend manually creates a JSON response using string concatenation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ BAD: Manual string concatenation with user input\nconst userRole = getUserRoleInput(); \/\/ User inputs: user\" }, \"role\": \"admin\", \"x\": \"\nconst responseJson = `{\"user\": \"${userRole}\", \"status\": \"active\"}`;<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the attacker crafts their input string carefully, they can break out of the intended key\/value structure and inject new parameters:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>Resulting concatenated string:\n{\"user\": \"user\" }, \"role\": \"admin\", \"x\": \"\", \"status\": \"active\"}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">When this string is later parsed down the line, the injected <code>\"role\": \"admin\"<\/code> key can override security logic.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Prevention<\/strong>: <strong>Never manually concatenate JSON strings.<\/strong> Always construct native data objects in your programming language first, then serialize them using standard built-in functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Pros &amp; Cons of JSON<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">While <strong>JSON <\/strong>is the undisputed standard for modern web applications, no technology is a one-size-fits-all solution. Understanding its strengths and limitations will help you decide when to use <strong>JSON <\/strong>and when an alternative format might be better suited.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advantages of JSON<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">1. Highly Readable &amp; Intuitive<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>JSON\u2019s <\/strong>clean key\/value syntax closely mimics natural data representation in modern programming languages. Unlike XML or binary formats, human developers can open a raw <code>.json<\/code> file and immediately understand its structure without specialized decoding tools.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">2. Lightweight with Minimal Overhead<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>JSON <\/strong>does not rely on verbose closing tags (e.g., <code>&lt;user&gt;&lt;name&gt;Alex&lt;\/name&gt;&lt;\/user&gt;<\/code>). Its compact syntax reduces payload sizes significantly, saving bandwidth and lowering latency over network connections.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3. Native Compatibility with JavaScript<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Because <strong>JSON <\/strong>is derived directly from JavaScript object literal syntax, web browsers can parse and serialize it natively without requiring external libraries or heavy processing pipelines.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">4. Language-Agnostic Ecosystem<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Virtually every major programming language like Python, Java, Go, C#, PHP, Rust, has native or standard library support for JSON serialization and deserialization, making it an ideal intermediate medium for cross-stack communication.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">5. Native Database Support<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Modern database engines including NoSQL databases like <strong>MongoDB<\/strong> (which uses <strong>BSON<\/strong>, a binary variant of <strong>JSON<\/strong>) and relational databases like <strong>PostgreSQL<\/strong> and <strong>MySQL<\/strong>, support <strong>JSON <\/strong>columns natively, allowing you to query nested <strong>JSON <\/strong>fields directly using SQL.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Disadvantages &amp; Limitations of JSON<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">1. Verbose for High-Frequency Big Data<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">While JSON is lighter than XML, it is still a <strong>text-based format<\/strong>. Sending large datasets repeatedly over network sockets transfers key names over and over again (<code>\"username\": \"a\"<\/code>, <code>\"username\": \"b\"<\/code>). For high-performance microservices, binary protocols like <strong>Protocol Buffers (Protobuf)<\/strong> or <strong>MessagePack<\/strong> offer up to 6\u201310\u00d7 faster transfer speeds.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">2. Restricted Data Types and Strict Syntax Standard<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>JSON <\/strong>only supports six basic data types (<code>String<\/code>, <code>Number<\/code>, <code>Boolean<\/code>, <code>Array<\/code>, <code>Object<\/code>, <code>Null<\/code>). <strong>JSON <\/strong>is notoriously unforgiving of minor syntax errors: It lacks native representation for:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dates\/Time:<\/strong> Must be sent as ISO strings (e.g., <code>\"2026-08-05T20:21:00Z\"<\/code>) or epoch timestamps.<\/li>\n\n\n\n<li><strong>Binary Data:<\/strong> Images or file buffers must be converted to Base64 strings, increasing file sizes by ~33%.<\/li>\n\n\n\n<li><strong>Exact Precision Decimals:<\/strong> Large numeric values can suffer from IEEE-754 floating-point precision loss during parsing.<\/li>\n\n\n\n<li>Comments (<code>\/\/<\/code> or <code>\/* *\/<\/code>) are forbidden.<\/li>\n\n\n\n<li>Trailing commas (<code>{\"a\": 1,}<\/code>) break parsers completely.<\/li>\n\n\n\n<li>Single quotes (<code>'key'<\/code>) trigger fatal syntax errors.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">3. Large File Size &amp; Bandwidth Waste (Redundant Keys)<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Because JSON is plain text and self-describing, <strong>field names are repeated for every single object in an array<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In massive datasets containing thousands of records, repeating verbose key names like <code>\"customerAccountBalanceNumber\"<\/code> consumes significant network bandwidth. Formats like CSV or binary protocols specify column\/field names <strong>once<\/strong> in a header\/schema, drastically reducing payload size.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">4. High CPU &amp; Memory Overhead for Parsing<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Parsing a JSON document requires scanning text character-by-character to validate syntax, construct objects, and allocate memory.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Converting a multi-megabyte JSON string into native language objects strains CPU and RAM, especially on resource-constrained devices like smartphones or IoT sensors, so the alternative is zero-copy binary serialization formats (like <strong>FlatBuffers<\/strong> or <strong>Cap&#8217;n Proto<\/strong>) allow applications to access data fields directly in memory without executing a costly deserialization parsing step.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">5. Limited Number Precision &amp; Risk of Data Loss<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">JSON specifies numbers as standard numeric literals without distinguishing between integers, floats, or high-precision decimals.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most JavaScript environments parse numbers as IEEE-754 double-precision floats. Numbers larger than <code>2<sup>53<\/sup><\/code> &#8211; 1 (like 64-bit database IDs e.g., <code>9007199254740993<\/code>) lose precision when parsed in JS. The solution is backend developers are forced to serialize large 64-bit integers or exact financial decimals as strings (<code>\"9007199254740993\"<\/code>), bypassing <strong>JSON&#8217;s <\/strong>native number support entirely to avoid data corruption.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">6. Inefficient for Binary Media Transmission<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">If your web application needs to send image data, audio files, or raw PDF buffers alongside structured data over JSON, it faces a major performance penalty. Since JSON is strictly text-based, binary bytes must be encoded into <strong>Base64 strings<\/strong>. With result being, base64 encoding inflates raw file sizes by roughly <strong>33%<\/strong>, increasing network load. Formats like <strong>BSON<\/strong> or <strong>Multipart Form-Data<\/strong> stream raw binary bytes without size inflation.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">7. No Built-In Namespace Support<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Unlike XML (which features XML Namespaces <code>xmlns<\/code> to merge data from multiple domain sources without key name collisions), <strong>JSON <\/strong>has no native concept of namespaces. If you merge multiple JSON data streams, identical key names (like <code>\"id\"<\/code> or <code>\"type\"<\/code>) will collide or overwrite each other unless developers manually prefix keys (e.g., <code>\"user_id\"<\/code> vs <code>\"order_id\"<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Over two decades after its creation, <strong>JSON <\/strong>remains the foundational medium for web data exchange. It successfully solved one of software engineering&#8217;s hardest communication challenges: getting vastly different technology stacks to talk to one another over a network without friction or heavy parsing overhead. By striking the ideal balance between <strong>human readability<\/strong> for developers and <strong>machine efficiency<\/strong> for computers, JSON effectively displaced XML and became the default standard for <strong>Document-oriented databases<\/strong> like MongoDB, <strong>RESTful APIs<\/strong> and modern web services and <strong>Configuration management<\/strong> across developer toolchains (<code>package.json<\/code>, <code>tsconfig.json<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Thanks for sticking around! Here\u2019s hoping your next data exchange is seamless, swift, and entirely exception-free.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>An Introduction to JSON: How Web Apps Exchange Data Building a web application today is like assembling an international team- [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"disabled","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[85],"tags":[20,90,91,95,92,86,84,96,89,88,94,93,87,97],"class_list":["post-208","post","type-post","status-publish","format-standard","hentry","category-json","tag-api","tag-apis-and-datas","tag-backend-development","tag-data-serialization","tag-full-stack-development","tag-javascript","tag-json","tag-jsonschema","tag-python","tag-software-wngineering","tag-system-design","tag-web-apis","tag-web-developement","tag-webdevforbeginners"],"_links":{"self":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/208","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/comments?post=208"}],"version-history":[{"count":9,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/208\/revisions"}],"predecessor-version":[{"id":225,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/208\/revisions\/225"}],"wp:attachment":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/media?parent=208"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/categories?post=208"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/tags?post=208"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}