PageSourceSearch

https://json-5.com/_next/static/chunks/pages/what-is-json-236b9f3cd2f2cbb6.js

js json-5.com collected 2026-09-25 15:19:51 UTC 21,295 bytes, 137 lines download raw bytes

1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[982],{2384:(e,s,a)=>{"use strict";a.d(s,{RO:()=>n.RO,fc:()=>n.Ay});var n=a(87673)},3849:()=>{Prism.languages.json={property:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,lookbehind:!0,greedy:!0},string:{pattern:/(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,lookbehind:!0,greedy:!0},comment:{pattern:/\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,greedy:!0},number:/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,punctuation:/[{}[\],]/,operator:/:/,boolean:/\b(?:false|true)\b/,null:{pattern:/\bnull\b/,alias:"keyword"}},Prism.languages.webmanifest=Prism.languages.json},24399:(e,s,a)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/what-is-json",function(){return a(27635)}])},27635:(e,s,a)=>{"use strict";a.r(s),a.d(s,{default:()=>x});var n=a(4930);a(67351);var i=a(65162),r=a(33695),t=a(43523),o=a(8991),c=a.n(o);a(67872),a(3849);var l=a(4577),d=a.n(l);a(46597),a(21089);var h=a(97847),u=a.n(h),j=a(2384);let{Title:p,Paragraph:g,Text:m,Link:b}=r.A,x=e=>{let{className:s}=e;(0,i.useEffect)(()=>{c().highlightAll()},[]);let a=(0,n.jsxs)("div",{children:[(0,n.jsxs)(u(),{children:[(0,n.jsx)("title",{children:"JSON Tutorial from the Basics to Real-World Use Cases in 2026"}),(0,n.jsx)(t.bx,{domain:"json-5.com",path:"what-is-json"}),(0,n.jsx)("meta",{name:"description",content:"Learn JSON from scratch to mastery with this comprehensive tutorial. Covers all levels, from beginner to advanced. Includes instructions and real-world examples."})]}),(0,n.jsx)(t.sT,{title:(0,n.jsx)(n.Fragment,{children:"The Ultimate JSON Tutorial, from the Basics to Real-World Use Cases in 2026"}),subTitle:"Structure JSON data safely and efficiently, and gain a deeper understanding with real-world applications"}),(0,n.jsx)("h2",{children:"Introudction"}),(0,n.jsx)(g,{children:"In web development, sharing data between servers and clients is really important. When it comes to doing this in a lightweight way, JSON (JavaScript Object Notation) is the star. JSON has become the go-to choice for sharing data because it's not heavy, easy for people to understand, and it works well with various systems. It doesn't waste time or resources and works smoothly with JavaScript, making data handling in web applications simpler."}),(0,n.jsx)("h2",{children:"What's JSON: The Basics"}),(0,n.jsx)(g,{children:"JSON, stands for JavaScript Object Notation, but don't be misled by the name; it's not just for JavaScript. JSON serves as a common language for data, making it easy for both humans and machines to work with. JSON can be also used with many different programming languages and systems."}),(0,n.jsx)(g,{children:"JSON is constructed around two key concepts:"}),(0,n.jsxs)(g,{children:[(0,n.jsx)("b",{children:"Objects"}),": Think of an object as a container filled with labeled items. Each label is a string, and within the container, you can store various data types such as text, numbers, or even more containers. These labels and data are separated by colons and commas. Here's an example of a JSON object:",(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`{
2  "name": "Alice",
3  "age": 30,
4}`})})]}),(0,n.jsxs)(g,{children:[(0,n.jsx)("b",{children:"Arrays"}),": An array is like a list of things. These things can be anything, like numbers, words, or even more lists. They're organized with square brackets and separated by commas."]}),(0,n.jsxs)(g,{children:["Here's an example of a JSON array:",(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:'[23, 21, 33, "Alice", "Bob", true]'})})]}),(0,n.jsx)("h2",{children:"Accessing JSON Data in JavaScript"}),(0,n.jsx)(g,{children:"Retrieving a complex JSON data in JavaScript is a common task in web development. We will then explore various techniques to query JSON data using JavaScript. We will cover topics such as accessing JSON data using string index and key directly, querying JSON data with unknown keys, retrieving nested data using key paths, and looping through JSON objects and arrays."}),(0,n.jsx)("h3",{children:"Getting JSON Data Using String Index and Key Directly"}
4),(0,n.jsx)(g,{children:'One of the simplest ways to access JSON data is by using the key directly or using string index notation. For example, if you have a JSON object obj and you want to access the value associated with the key "name," you can do it like this:'}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const obj = {"name": "Alice"};
5const name = obj["name"]; // using string index notation
6const name = obj.name; // using the key directly
7`})}),(0,n.jsx)("h3",{children:"Getting JSON Data Using an Unknown Key"}),(0,n.jsx)(g,{children:"Sometimes, you may not know the exact key you need to access in advance. In such cases, you can use a variable to dynamically access the JSON data. For instance:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const variableKey = "dynamicKey";
8const value = obj[variableKey];`})}),(0,n.jsx)("h3",{children:"Getting JSON Data by Key Path"}),(0,n.jsx)(g,{children:'JSON data can be nested, and you may need to access values deep within the complex structure. However, If you try to access properties or methods of an undefined value, you will receive this error: "Cannot read properties of undefined".'}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`let obj = { };
9console.log(obj.key1.key2); // Cannot read properties of undefined (reading 'key2')`})}),"Solutuon 1: make sure to check if the variable is defined before accessing its properties.",(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:"console.log(obj && obj.key1 && obj.key1.key2); // undefined (no error)"})}),"Solutuon 2: use libraries like ",(0,n.jsx)(t.Gr,{href:"https://npm-compare.com/lodash,underscore",children:"lodash or underscore"}),":",(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`import _ from 'lodash'; // or using 'underscore'
10console.log(_.get(obj, 'key1.key2')); // undefined (no error)`})}),"Solutuon 3: use ",(0,n.jsx)(t.Gr,{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining",children:"optional chaining operator"}),":",(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:"console.log(obj?.key1?.key2); // undefined (no error)"})}),(0,n.jsx)(g,{children:"If you're trying to decide which solution is better, here are a few things to consider:"}),(0,n.jsxs)(g,{children:["The ",(0,n.jsx)("code",{children:"obj && obj.key1 && obj.key1.key2"})," approach has broad browser support and minimal bundle size impact but may be slightly more verbose."]}),(0,n.jsxs)(g,{children:[(0,n.jsx)(t.Gr,{href:"https://npm-compare.com/lodash",children:"Lodash"}),", being a widely-used library, has broader browser support. It is compatible with most modern browsers as well as older versions. However, using lodash might increase the overall bundle size (1.41 MB Unpacked Size) of your application."]}),(0,n.jsxs)(g,{children:["Finally, the optional chaining operator (?.)  was introduced in ",(0,n.jsx)(t.Gr,{href:"https://tc39.es/ecma262/2020/#sec-left-hand-side-expressions-static-semantics-early-errors",children:"ECMAScript 2020"})," and is supported in modern browsers like Chrome (80+), Edge (80+), and Firefox (74+). However, it may not work in older versions of browsers."]}),(0,n.jsx)("h3",{children:"Looping Through a JSON Object"}),(0,n.jsxs)(g,{children:["you can loop through a JSON object using ",(0,n.jsx)("code",{children:"for...in"})," loop to iterate through the object's properties."]}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const jsonObj = {
11  name: 'John',
12  age: 30,
13  city: 'New York'
14};
15
16for (let key in jsonObj) {
17  const value = jsonObj[key];
18  console.log(key, value);
19}
20`})}),(0,n.jsx)(g,{children:"Or using lodash:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`_.forEach(obj, function(value,key) {
21    console.log(key, value)
22});`})}),(0,n.jsx)("h3",{children:"Looping Through a JSON Array"}),(0,n.jsxs)(g,{children:["Looping through a JSON array in JavaScript can be done using a ",(0,n.jsx)("code",{children:"for"})," loop:"]}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const jsonArray = [
23  { name: 'John', age: 30, city: 'New York' },
24  { name: 'Alice', age: 25, city: 'Los Angeles' },
25];
26
27for (let index = 0; index < jsonArray.length; index++) {
28  const item = jsonArray[i];
29  console.log(index, item);
30}`})}),(0,n.jsx)(g,{children:"Alternatively, you can use the forEach method for a more concise approach:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`jsonArray.forEach((item, index) => {
31  console.log(index, item);
32});`})}),(0,n.jsx)("h2",{children:"Manipulate JSON Data in JavaScript"}),(0,n.jsx)(g,{children:"In web development, manipulating JSON data often includes tasks like adding, updating, or deleting properties."}),(0,n.jsx)("h3",{children:"Defining an Object with Static Keys"}),(0,n.jsx)(g,{children:"Creating a JSON object with static keys is straightforward. You simply define the object with fixed key-value pairs. For example:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:'const obj = { "key1": 1 };'})}),(0,n.jsx)("h3",{children:"Defining an Object with Dynamic Keys"}),(0,n.jsx)(g,{children:"If You need to create a JSON object with keys that are determined dynamically:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const variableKey = 'dynamicKey';
33const obj = { [variableKey]: 1 };`})}),(0,n.jsx)("h3",{children:"Dynamically Adding a Property to an Existing Object"}),(0,n.jsx)(g,{children:"You can add properties to an existing JSON object using the dot notation or square brackets:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const obj = { key1: 1 }; // existing object
34obj.key2 = 2; // dot notation
35obj['key3'] = 'value'; // square brackets`})}),(0,n.jsx)("h3",{children:"Removing a Key from an Object"}),(0,n.jsx)(g,{children:"To remove a key from a JSON object, you can use the delete operator:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const obj = { "key1": 1 };
36delete obj.key1;`})}),(0,n.jsx)("h3",{children:"Merging Two Objects"}),(0,n.jsx)(g,{children:"When you have multiple JSON objects and want to combine their properties:"}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const object1 = {"a": 1};
37const object2 = {"b": 2};
38const mergedObject = { ...object1, ...object2 }; // {"a": 1, "b": 2}`})}),(0,n.jsx)("h2",{children:"Serialization and Deserialization of JSON in JavaScript"}),(0,n.jsxs)(g,{children:["JSON is a popular format for representing and transmitting data between a server and a client. Serialization allows you to convert JavaScript objects into a JSON string that can be easily sent to the server. Deserialization, on the other hand, helps you convert received JSON data back into JavaScript objects for processing on the client-side.",(0,n.jsx)(t.NC,{imgWidth:450,fileName:"61add845309d33386dec467dcbb1d4c0.png",desc:"Data Interchange Between Browser and Server"})]}),(0,n.jsxs)(g,{children:[(0,n.jsx)("h3",{children:"JSON Serialization: Using Standard JavaScript Utility"}),"Use ",(0,n.jsx)("code",{children:"JSON.stringify()"})," to convert object into string:"]}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const json = {
39  "name": "Alice",
40  "age": 30,
41};
42JSON.stringify(json); // returns string: '{"name":"Alice","age":30}'
43`})}),(0,n.jsx)("h3",{children:"JSON Serialization: Using More Efficient and Safer JSON Utility"}),(0,n.jsxs)(g,{children:["While JavaScript provides the built-in ",(0,n.jsx)("code",{children:"JSON.stringify()"})," method for this task, there are situations where you might want to consider using specialized libraries like ",(0,n.jsx)(t.Gr,{href:"https://npm-compare.com/fast-safe-stringify,json-stringify-safe,fast-json-stringify",children:"fast-safe-stringify, json-stringify-safe, and fast-json-stringify"}),"."]}),(0,n.jsxs)(g,{children:[(0,n.jsx)("ul",{children:(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Handling Circular References"}),": Circular references occur when objects refer back to themselves, causing issues during standard JSON serialization. Libraries like ",(0,n.jsx)("code",{children:"fast-safe-stringify"})," and offer a safe way to serialize objects with circular references, ensuring application won't break."]})}),(0,n.jsx)("ul",{children:(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Improved Performance"}),":",(0,n.jsx)("code",{children:"fast-json-stringify"})," focus on optimizing the serialization process for high performance. If you need fast serialization of large objects, this library may offer the high performance serialization."]})})]}),(0,n.jsx)("h3",{children:"JSON Deserialization: Using Standard JavaScript Utility"}),(0,n.jsxs)(g,{children:[(0,n.jsx)("code",{children:"JSON.parse()"})," is the reverse process, where a JSON string is converted back into a data structure or object that can be used in a JavaScript."]}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const str = '{"name":"Alice","age":30}';
44JSON.parse(str); // returns json object: {"name":"Alice","age":30}
45`})}),(0,n.jsx)("h3",{children:"JSON Deserialization: Using More Efficient and Safer JSON Utility"}),(0,n.jsxs)(g,{children:["While JavaScript provides the built-in ",(0,n.jsx)("code",{children:"JSON.parse()"})," method to deserialize JSON string, there are some libraries like ",(0,n.jsx)(t.Gr,{href:"https://npm-compare.com/secure-json-parse,fast-json-parse",children:"secure-json-parse and fast-json-parse"})," could help you do it more efficient and safer."]}),(0,n.jsxs)(g,{children:[(0,n.jsx)("ul",{children:(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Improved Security"}),": Libraries like ",(0,n.jsx)("code",{children:"secure-json-parse"})," are designed with a focus on data security issue such as ",(0,n.jsx)(t.Gr,{href:"https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting",children:"XSS"}),"."]})}),(0,n.jsx)("ul",{children:(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Robust Error Handling"}),": It can be hard to parse JSON strings with the built-in ",(0,n.jsx)("code",{children:"JSON.parse()"})," function, especially when the data is complex or wrong.",(0,n.jsx)("code",{children:"secure-json-parse"})," make it easier to find and fix errors by offering more robust error handling mechanism."]})}),(0,n.jsx)("ul",{children:(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Improved Performance"}),":",(0,n.jsx)("code",{children:"fast-json-parse"})," can make JSON parsing much faster. If you need to parse a lot of JSON data quickly, this library may be the best option for you."]})})]}),(0,n.jsx)("h2",{children:"Real-World Use Cases of JSON"}),(0,n.jsx)(g,{children:"JSON is used everywhere in frontend and backend development:"}),(0,n.jsx)(g,{children:(0,n.jsxs)("ul",{children:[(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"APIs"}),": Most web services use JSON to talk to each other. When you visit a website, the data you see is often in JSON format.",(0,n.jsx)(t.NC,{imgWidth:550,fileName:"125afb8875103b7b96a3a13def2a0eae.png",desc:"JSON Data in API Request"})]}),(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Configuration Files"}),": Many apps use JSON for their settings because it's easy for people to understand.  npm package.json",(0,n.jsx)(t.NC,{imgWidth:550,fileName:"03271996e1315e020f792e5a18c4abe1.png",desc:"JSON Data in npm package.json"})]}),(0,n.jsxs)("li",{children:[(0,n.jsx)("b",{children:"Data Storage"}),": Some databases such as ",(0,n.jsx)(t.Gr,{href:"https://www.mongodb.com",children:"MongoDB"})," use a close cousin of JSON called ",(0,n.jsx)(t.Gr,{href:"https://bsonspec.org",children:"BSON"})," (Binary JSON) to store data.",(0,n.jsx)(t.NC,{imgWidth:550,fileName:"557db9d865daff3328ae112be653280a.png",desc:"BSON Data in mongodb"})]})]})}),(0,n.jsx)("h2",{children:"JSON and NoSQL Databases"}),(0,n.jsx)(g,{children:"Using JSON in NoSQL databases is beneficial in some applications since JSON could be used in the flexible and schema-free databases."}),(0,n.jsx)("h3",{children:"Use Case 1: Store Extra User Profiles"}),(0,n.jsx)(g,{children:"In a collection of user profiles, some users might have extra details, like email addresses, while others don't. JSON format is one of the best format thanks to its sc
45hema flexibility."}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`// Example using MongoDB and Node.js
46const MongoClient = require('mongodb').MongoClient;
47const url = 'mongodb://localhost:27017'; // Database connection URL
48
49MongoClient.connect(url, (err, client) => {
50  if (err) throw err;
51
52  const db = client.db('mydatabase'); // Use your database name
53  const collection = db.collection('userProfiles'); // Use your collection name
54
55  // JSON user profile data
56  const user1 = {
57    "username": "bob",
58    "age": 30,
59    "email": "[email protected]",
60  };
61  const user2 = {
62    "username": "alice",
63    "age": 31,
64  };
65
66  // Insert the user profiles into the collection
67  collection.insertOne(user1);
68  collection.insertOne(user2);
69});`})}),(0,n.jsx)("h3",{children:"Use Case 2: Find Article via Tag in Blog System"}),(0,n.jsx)(g,{children:'A blog system might store articles in a NoSQL database using JSON, where each article can have different metadata such tags. One article has an additional "tags" field, which represents a semi-structured aspect of the data. We insert these articles into a MongoDB collection and retrieve them via tag name.'}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const MongoClient = require('mongodb').MongoClient;
70const url = 'mongodb://localhost:27017'; // Database connection URL
71
72MongoClient.connect(url, (err, client) => {
73  if (err) throw err;
74
75  const db = client.db('mydatabase'); // Use your database name
76  const collection = db.collection('articles'); // Use your collection name
77
78  // Example JSON data with unstructured and semi-structured content
79  const article1 = {
80    "title": "Introduction to NoSQL Databases",
81    "author": "John Doe",
82    "content": "NoSQL databases come in many varieties, each designed for specific use cases."
83  };
84
85  const article2 = {
86    "title": "Exploring JSON",
87    "author": "Jane Smith",
88    "content": "JSON is a popular format, known for its flexibility. See http://json-5.com"
89  };
90
91  const article3 = {
92    "title": "Web Development Best Practices",
93    "author": "Robert Johnson",
94    "content": "In modern web development, best practices emphasize security, scalability, and user experience.",
95    "tags": ["web development", "best practices", "security"]
96  };
97
98  // Insert articles into the collection
99  collection.insertMany([article1, article2, article3]);
100
101  // Query and retrieve articles by tag
102  collection.find({ tags: "web development" }).toArray((err, articles) => {
103    console.log(articles)
104  });
105});
106`})}),(0,n.jsx)("h3",{children:"Use Case 3: NOSQL Integration with RESTful APIs "}),(0,n.jsx)(g,{children:"As mentioned above, JSON is the most widely used data format for APIs, particularly for RESTful web services. Using JSON in NoSQL databases makes it easier to exchange data between the database and the application."}),(0,n.jsx)("pre",{children:(0,n.jsx)("code",{className:"language-javascript",children:`const express = require('express');
107const { MongoClient } = require('mongodb');
108const app = express();
109const port = 3000; // Replace with your desired port
110
111// MongoDB connection URL
112const mongoUri = 'mongodb://localhost:27017';
113
114// Connect to MongoDB
115MongoClient.connect(mongoUri, { useUnifiedTopology: true })
116  .then(client => {
117    console.log('Connected to MongoDB');
118    const db = client.db('mydatabase'); // Use your database name
119    const collection = db.collection('data'); // Use your collection name
120
121    // Middleware for parsing JSON data in requests
122    app.use(express.json());
123
124    // Define a route to retrieve data from MongoDB
125    app.get('/api/data', async (req, res) => {
126      const data = await collection.find({}).toArray();
127      res.json(data);
128    });
129
130    app.listen(port, () => {
131      console.log("Server is running");
132    });
133  })
134  .catch(err => {
135    console.error('Error connecting to MongoDB:', err);
136  });
137`})}),(0,n.jsx)("h2",{children:"Conclusion"}),(0,n.jsx)(g,{children:"JSON is a widely used data format in web development due to its simplicity, human-readability, and cross-language compatibility. It is an essential tool for data interchange and communication in modern web applications."})]});return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(j.fc,{}),(0,n.jsx)("div",{className:d()("json-vs-json5",s),children:a})]})}},67351:()=>{}},e=>{e.O(0,[482,476,673,636,593,792],()=>e(e.s=24399)),_N_E=e.O()}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.