JSON (JavaScript Object Notation) is a text-based data format used to store and transfer data. It's widely used for communication between web servers and clients due to its simplicity and compatibility with JavaScript.
// A simple JSON example representing a person { "name": "Alice", // Key-value pair with string value "age": 30, // Number value "isStudent": false // Boolean value }
JSON was introduced in the early 2000s by Douglas Crockford as a lightweight alternative to XML for data interchange. It gained popularity due to its easy syntax and native support in JavaScript.
// Example: JSON in early AJAX usage (used in browser-server communication) let jsonString = '{"city":"Toronto","temp":25}'; // JSON string received from server let data = JSON.parse(jsonString); // Convert JSON string to JavaScript object console.log(data.city); // Outputs: Toronto
JSON is easier to read and write than XML, uses less bandwidth, and is directly usable in JavaScript. XML is more verbose and supports attributes and schemas but is harder to parse in many cases.
// JSON format { "product": "Book", "price": 15.99 } // Equivalent XML <product> <name>Book</name> <price>15.99</price> </product>
JSON supports the following data types: strings, numbers, objects, arrays, booleans, and null.
// Example of all JSON data types { "string": "hello", // String "number": 42, // Number "boolean": true, // Boolean "array": [1, 2, 3], // Array "object": {"a": 1}, // Object "nullValue": null // Null }
JSON must use double quotes for keys and strings, use commas to separate items, and follow strict syntax rules. No comments or functions are allowed inside JSON.
// Correct JSON { "title": "Example", "value": 123 } // Incorrect JSON (with single quotes, comments, and trailing comma) - INVALID // { // 'title': 'Example', // Wrong quotes // 'value': 123, // Trailing comma // // Comment not allowed // }
JSON is built using key-value pairs, where each key is a string and the value can be any JSON data type. The key and value are separated by a colon.
// Key-value pair example { "language": "English", // "language" is the key, "English" is the value "score": 95 // "score" is the key, 95 is the value }
JSON is lightweight because it uses minimal formatting and omits unnecessary markup. This makes it efficient for network transmission and easy for machines to parse.
// Lightweight compared to XML { "name": "Laptop", "price": 899 } // Minimal brackets and tags make JSON lightweight
JSON is used in APIs, web services, configuration files, mobile apps, and databases like MongoDB. It’s everywhere in modern web development.
// Example: JSON response from an API { "userId": 101, "username": "majid_dev", "email": "majid@example.com" } // This might be returned from a user API endpoint
JSON is human-readable, easy to parse, compact, language-independent, and natively supported by JavaScript. These benefits make it ideal for data exchange across platforms.
// Sending JSON data with JavaScript let payload = { "title": "Submit", "status": "success" }; fetch("/api/save", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) // Convert JS object to JSON string });
Some think JSON supports comments or allows trailing commas—this is false. Others believe it's only for JavaScript, but it's widely used in Python, Java, and more.
// Misconception: JSON supports comments — INVALID /* { "item": "pen", // This comment is invalid in JSON } */ // Correct way: no comments { "item": "pen" }
JSON objects are collections of key-value pairs enclosed in curly braces {}
. Keys must be strings and values can be any valid JSON data type.
// Example JSON object { "name": "John", // String key with string value "age": 28, // String key with number value "isEmployee": true // Boolean value }
JSON arrays are ordered lists of values enclosed in square brackets []
. They can contain any combination of valid JSON data types.
// Example JSON array { "colors": ["red", "green", "blue"] // Array of strings }
JSON allows nesting objects and arrays to represent complex data hierarchies, such as embedded records or lists of items.
// Nested JSON with object and array inside { "user": { "id": 1, "name": "Alice" }, "hobbies": ["reading", "gaming", "cycling"] }
In JSON, strings must be enclosed in double quotes. Special characters like quotes or new lines must be escaped using a backslash (e.g., \n
, \"
).
// Escaping characters in a string { "quote": "He said, \"Hello world!\"\nNew line here." }
JSON supports two Boolean values: true
and false
. It also supports null
to represent empty or unknown values.
// Using Boolean and Null in JSON { "isOnline": false, "lastLogin": null }
Whitespace such as spaces, tabs, and newlines can be used freely in JSON to improve readability. JSON parsers ignore whitespace outside of strings.
// Whitespace makes this JSON more readable { "title": "Book", "author": "Majid", "pages": 250 }
JSON does not allow comments. Including comments in JSON will result in parsing errors, unlike JavaScript or other programming languages.
// INVALID: Comments are not allowed in JSON /* { "valid": true // this comment would break the JSON } */ // VALID JSON without comments { "valid": true }
JSON linting tools are used to validate and format JSON code. They help detect syntax errors and make your JSON more readable.
// Online JSON Linting Example (not actual code) // Paste into https://jsonlint.com/ { "name": "Validator", "valid": true }
Pretty-printed JSON is spaced out for human readability, while minified JSON removes whitespace to save space, often used in production.
// Pretty printed JSON { "name": "Pretty", "format": "readable" } // Minified JSON {"name":"Pretty","format":"readable"}
JSON Schema defines the structure of JSON data: required keys, data types, and constraints. It’s useful for validation and documentation.
// Example JSON Schema { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "required": ["name", "age"] }
JSON Schema is a vocabulary used to validate the structure and content of JSON data. It defines expected types, required fields, formats, and constraints, making your data more predictable and secure.
// Basic JSON Schema definition { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", // The root JSON must be an object "properties": { "name": { "type": "string" }, // 'name' must be a string "age": { "type": "number" } // 'age' must be a number }, "required": ["name"] // 'name' is required }
Validation ensures your JSON follows expected rules. Tools like AJV or Python's `jsonschema` validate actual data against your schema definition.
// Sample data to validate { "name": "Sarah", "age": 28 } // If validated against previous schema, this is valid JSON // Missing "name" would cause validation to fail
JSON Schema supports types like string, number, boolean, array, and object. You can also set constraints such as minLength, maxLength, minimum, maximum, etc.
// Schema with constraints { "type": "object", "properties": { "username": { "type": "string", "minLength": 3, "maxLength": 15 }, "age": { "type": "number", "minimum": 18, "maximum": 99 } } }
The `required` keyword specifies which properties must be included in the JSON. Missing any of them results in a validation error.
// Schema requiring both fields { "type": "object", "properties": { "email": { "type": "string" }, "password": { "type": "string" } }, "required": ["email", "password"] // Both must be present }
You can enforce regex patterns or use standard formats like "email", "uri", "date", etc., to validate string fields in JSON.
// Schema with pattern and format { "type": "object", "properties": { "email": { "type": "string", "format": "email" // Must be a valid email }, "postalCode": { "type": "string", "pattern": "^[0-9]{5}$" // Must be a 5-digit number } } }
Conditional validation uses `if`, `then`, and `else` to apply rules depending on property values.
// Conditional validation example { "type": "object", "properties": { "role": { "type": "string" }, "adminCode": { "type": "string" } }, "if": { "properties": { "role": { "const": "admin" } } }, "then": { "required": ["adminCode"] // 'adminCode' is required if role is 'admin' } }
You can combine schemas to validate against multiple criteria using `allOf`, `anyOf`, and `oneOf`.
// Using oneOf { "type": "object", "properties": { "identifier": { "oneOf": [ { "type": "string", "pattern": "^[A-Z]{3}$" }, { "type": "number", "minimum": 100 } ] } } } // Valid if 'identifier' is either a 3-letter string or a number >= 100
External references (`$ref`) allow reusing schema definitions across files. Useful for large, modular schema designs.
// Main schema { "$ref": "user.schema.json" // Reference to external schema file } // user.schema.json (external) { "type": "object", "properties": { "username": { "type": "string" }, "email": { "type": "string", "format": "email" } }, "required": ["username", "email"] }
JSON Schema evolves over time. You can specify the version using the `$schema` property to ensure compatibility with specific drafts (e.g., draft-07, draft-2020-12).
// Example using draft-07 { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "id": { "type": "number" } } }
Popular tools include:
// Example: AJV validation in JavaScript const Ajv = require("ajv"); const ajv = new Ajv(); const schema = { type: "object", properties: { age: { type: "number" } }, required: ["age"] }; const validate = ajv.compile(schema); const data = { age: 22 }; console.log(validate(data)); // true if valid
This method converts a JavaScript object into a JSON string, which is useful for sending data to a server or storing it as a string.
// JavaScript object let user = { name: "Alice", age: 25 }; // Convert object to JSON string let jsonString = JSON.stringify(user); console.log(jsonString); // Output: {"name":"Alice","age":25}
This method converts a JSON string back into a JavaScript object, allowing you to access its data programmatically.
// JSON string let jsonString = '{"name":"Bob","age":30}'; // Convert to JavaScript object let obj = JSON.parse(jsonString); console.log(obj.name); // Output: Bob
JSON is a string format used to store or transmit data. JavaScript objects are native data structures. JSON must use double quotes for strings and keys.
// JavaScript object (can have single quotes and functions) let jsObj = { name: 'Charlie', greet: function() { console.log("Hi"); } }; // JSON string (only data, no functions, double quotes required) let json = '{"name":"Charlie"}';
You can include arrays in JSON, which makes it easy to represent lists. Arrays can hold objects, strings, numbers, etc.
// JSON array of objects let jsonString = '[{"name":"John"},{"name":"Jane"}]'; // Parse to JavaScript array let people = JSON.parse(jsonString); console.log(people[1].name); // Output: Jane
JavaScript can fetch JSON from web APIs using fetch()
. The response must be parsed with .json()
.
// Fetch data from an API fetch("https://api.example.com/data") .then(response => response.json()) // Parse JSON .then(data => { console.log(data); // Use the JSON data });
You can use console.log()
to inspect parsed JSON objects directly in your browser's developer console.
// JSON string let json = '{"fruit":"apple","price":2}'; // Parse and log it let obj = JSON.parse(json); console.log(obj); // Logs full object console.log(obj.fruit); // Logs: apple
Web browsers allow storing JSON data in localStorage as strings using setItem()
and getItem()
.
// JavaScript object let settings = { theme: "dark", fontSize: 14 }; // Save to localStorage localStorage.setItem("userSettings", JSON.stringify(settings)); // Retrieve from localStorage let stored = JSON.parse(localStorage.getItem("userSettings")); console.log(stored.theme); // Output: dark
Once JSON is parsed into a JS object, you can loop through keys using for...in
or through arrays with forEach
.
// JSON string let jsonString = '{"a":1,"b":2,"c":3}'; // Parse JSON let obj = JSON.parse(jsonString); // Loop through keys for (let key in obj) { console.log(key + ": " + obj[key]); // Output: a:1, b:2, c:3 }
Typical mistakes include using single quotes, trailing commas, or functions in JSON. JSON must be valid to parse correctly.
// Invalid JSON string (single quotes and trailing comma) let invalidJson = '{\'name\':\'Tom\',}'; // Will cause error // Correct version let validJson = '{"name":"Tom"}'; let user = JSON.parse(validJson); console.log(user.name); // Output: Tom
Use try...catch
to handle errors when parsing JSON, especially when working with unpredictable data from APIs.
let brokenJson = '{"age":25,'; // Malformed JSON try { let data = JSON.parse(brokenJson); } catch (error) { console.error("Error parsing JSON:", error.message); // Graceful error handling }
Python has a built-in json
module to parse JSON strings into Python dictionaries and convert dictionaries to JSON strings.
import json # JSON string json_str = '{"name": "Alice", "age": 30}' # Convert JSON string to Python dictionary data = json.loads(json_str) print(data["name"]) # Output: Alice # Convert Python dictionary to JSON string json_data = json.dumps(data) print(json_data) # Output: {"name": "Alice", "age": 30}
Java uses libraries like Jackson or Gson for working with JSON. These libraries allow mapping JSON to Java objects and vice versa.
// Using Gson library import com.google.gson.Gson; public class Main { public static void main(String[] args) { String json = "{\"name\":\"John\",\"age\":25}"; // Convert JSON to Java object Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class); System.out.println(person.name); // Output: John // Convert Java object to JSON String jsonString = gson.toJson(person); System.out.println(jsonString); } } class Person { String name; int age; }
PHP uses json_encode()
and json_decode()
for working with JSON data.
<?php // PHP array $data = array("name" => "Emma", "age" => 22); // Convert to JSON $json = json_encode($data); echo $json; // {"name":"Emma","age":22} // Decode JSON back to array $decoded = json_decode($json, true); echo $decoded["name"]; // Emma ?>
Ruby has a built-in json
module to parse and generate JSON.
require 'json' # Hash to JSON hash = { name: "Tom", age: 40 } json_data = hash.to_json puts json_data # {"name":"Tom","age":40} # JSON to Hash parsed = JSON.parse(json_data) puts parsed["name"] # Tom
C# uses System.Text.Json
or Newtonsoft.Json
to handle JSON serialization and deserialization.
using System.Text.Json; public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { string json = "{\"Name\":\"Lily\",\"Age\":29}"; // Deserialize Person p = JsonSerializer.Deserialize<Person>(json); Console.WriteLine(p.Name); // Output: Lily // Serialize string jsonString = JsonSerializer.Serialize(p); Console.WriteLine(jsonString); } }
In Node.js, JSON parsing and stringifying is built-in using JSON.parse()
and JSON.stringify()
.
// JSON string let jsonStr = '{"name": "Mark", "age": 32}'; // Convert JSON string to JavaScript object let obj = JSON.parse(jsonStr); console.log(obj.name); // Output: Mark // Convert object to JSON string let json = JSON.stringify(obj); console.log(json); // {"name":"Mark","age":32}
Go uses the encoding/json
package to encode and decode JSON using structs.
package main import ( "encoding/json" "fmt" ) type Person struct { Name string Age int } func main() { jsonStr := `{"Name":"Noah", "Age":35}` var p Person json.Unmarshal([]byte(jsonStr), &p) // Decode fmt.Println(p.Name) // Output: Noah newJson, _ := json.Marshal(p) // Encode fmt.Println(string(newJson)) }
In Swift, Codable
structs are used to serialize and deserialize JSON.
import Foundation struct Person: Codable { var name: String var age: Int } let jsonData = """ {"name": "Sophia", "age": 26} """.data(using: .utf8)! let decoder = JSONDecoder() let person = try! decoder.decode(Person.self, from: jsonData) print(person.name) // Sophia let encoder = JSONEncoder() let encodedData = try! encoder.encode(person) print(String(data: encodedData, encoding: .utf8)!)
In R, the jsonlite
package is commonly used to parse and generate JSON.
library(jsonlite) # R list to JSON data <- list(name="Liam", age=45) json <- toJSON(data) print(json) # JSON to R list parsed <- fromJSON(json) print(parsed$name) # Liam
Serialization converts data structures to JSON strings. Deserialization is the reverse—converting JSON strings into usable data structures.
// JavaScript example let person = { name: "Olivia", age: 28 }; // Serialization: object to JSON string let jsonString = JSON.stringify(person); console.log(jsonString); // {"name":"Olivia","age":28} // Deserialization: JSON string to object let newPerson = JSON.parse(jsonString); console.log(newPerson.name); // Olivia
A REST API (Representational State Transfer) is a set of rules that allow software to communicate over HTTP. REST APIs often exchange data in JSON format due to its simplicity and readability.
// Example: A REST API might respond with this JSON { "id": 1, "title": "Learn JSON", "completed": false }
APIs often return JSON to deliver structured data to clients. It enables seamless integration between frontend and backend systems.
// JSON response from GET /api/user/1 { "id": 1, "name": "Majid", "email": "majid@example.com" }
JavaScript’s Fetch API lets you send data in JSON format to web servers using POST, PUT, or PATCH methods.
// Sending JSON data to an API using Fetch fetch('/api/addUser', { method: 'POST', headers: { 'Content-Type': 'application/json' // Tell server the data format }, body: JSON.stringify({ name: "Alice", // Convert JS object to JSON age: 25 }) });
Both React and Vue fetch and use JSON data in their components to dynamically update the UI.
// React example (useEffect + fetch) useEffect(() => { fetch("/api/data") .then(res => res.json()) // Convert response to JSON .then(data => setData(data)); }, []);
// Vue example (mounted lifecycle hook) mounted() { fetch("/api/data") .then(res => res.json()) // Convert to JSON .then(data => { this.info = data; // Store in component data }); }
Axios is a promise-based HTTP client used to send and receive JSON data in JavaScript projects.
// Fetching JSON using Axios axios.get('/api/user/5') .then(response => { console.log(response.data); // JSON data returned by API }) .catch(error => { console.error(error); // Handle errors });
AJAX allows web pages to send/receive JSON data asynchronously, updating parts of the page without a full reload.
// Using AJAX (vanilla JS) to fetch JSON let xhr = new XMLHttpRequest(); xhr.open("GET", "/api/info", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { let jsonData = JSON.parse(xhr.responseText); // Parse JSON console.log(jsonData); } }; xhr.send();
Handling a JSON response involves converting the response string into a JavaScript object using res.json()
or JSON.parse()
.
// Handling JSON response with Fetch fetch("/api/stats") .then(response => response.json()) // Converts response to JS object .then(data => { console.log("Users:", data.users); });
JSON APIs should include useful error messages. Clients must check HTTP status codes and parse error responses accordingly.
// Example: Handling errors in Fetch fetch("/api/invalid") .then(response => { if (!response.ok) { throw new Error("API Error: " + response.status); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error("Fetch error:", error));
JWT is a compact JSON-based format used for securely transmitting user authentication data between client and server.
// Example JWT payload (after decoding) { "userId": 101, "username": "majid_dev", "role": "admin", "exp": 1713456000 // Expiration timestamp }
HTML responses are used for rendering views, while JSON responses provide data for frontend apps. JSON APIs are more suitable for SPAs, mobile apps, and JavaScript-heavy interfaces.
// HTML response (used for UI) <html><body><h1>Welcome User</h1></body></html> // JSON response (used for data) { "message": "Welcome User", "userId": 123 }
You can create a JSON file using any text editor. Save the file with a .json
extension and ensure the structure is valid.
// Contents of data.json { "title": "JSON Guide", "pages": 12 }
In the browser, JSON files are typically fetched using fetch()
or AJAX. You must parse the response into a JavaScript object.
// Fetching and reading JSON file in JavaScript fetch('data.json') .then(response => response.json()) // Parse the JSON response .then(data => console.log(data)); // Use the JSON data
In Node.js, you can use the built-in fs
module to write data to a JSON file using JSON.stringify()
.
// Writing to a JSON file using Node.js const fs = require('fs'); const obj = { name: "NodeJS", type: "Backend" }; fs.writeFileSync('output.json', JSON.stringify(obj, null, 2)); // Writes formatted JSON
Python uses the built-in json
module to read JSON files. Use json.load()
to parse file content.
# Reading a JSON file in Python import json with open('data.json', 'r') as file: data = json.load(file) # Parse JSON from file print(data["title"]) # Access JSON value
To safely edit JSON files, always read and parse the data first, modify the object, and then overwrite the file with the updated content.
// Example in Node.js const fs = require('fs'); let data = JSON.parse(fs.readFileSync('data.json', 'utf8')); data.pages = 20; // Modify the data fs.writeFileSync('data.json', JSON.stringify(data, null, 2)); // Save it back
To pretty-print JSON in the terminal, you can use command-line tools like jq
or python -m json.tool
.
// Using Python to pretty print cat data.json | python -m json.tool // Using jq cat data.json | jq .
JSON is commonly used in config files (e.g., package.json
in Node.js) to store project settings and dependencies.
// Example package.json snippet { "name": "my-project", "version": "1.0.0", "scripts": { "start": "node app.js" } }
Localization involves storing text in multiple languages. JSON is often used to map keys to translated text strings.
// en.json { "greeting": "Hello", "farewell": "Goodbye" } // fr.json { "greeting": "Bonjour", "farewell": "Au revoir" }
JSON files typically use a .json
extension. Relative or absolute paths can be used to access them in your code.
// Example in Node.js const config = require('./config/settings.json'); // Relative path // In Python with open('/home/user/settings.json') as f: data = json.load(f)
Use meaningful key names, validate data structures with JSON Schema, avoid large files, and maintain consistent formatting across your project.
// Tips // Use clear keys: "user_id" instead of "u" // Keep files small and modular // Use a schema for validation (e.g., Ajv or JSON Schema) // Always backup files before overwriting
NoSQL databases like MongoDB and CouchDB use JSON-like structures to store and manage data, allowing flexibility in schema design.
// Sample JSON document stored in a NoSQL database { "name": "Alice", "age": 30, "email": "alice@example.com" }
MongoDB stores data in BSON (Binary JSON), which extends JSON with additional data types such as Date and Binary, while maintaining JSON structure.
// MongoDB insertOne operation db.users.insertOne({ name: "John", age: 25, createdAt: new Date() // BSON-specific type });
CouchDB uses pure JSON documents as the primary storage format and interacts via HTTP API. Each document has a unique _id
.
// Example CouchDB document { "_id": "user_123", "name": "Emma", "role": "admin" }
PostgreSQL supports json
and jsonb
types, enabling you to store JSON objects in columns and efficiently query them.
-- Creating a table with a JSONB column CREATE TABLE users ( id SERIAL PRIMARY KEY, profile JSONB ); -- Inserting JSON data INSERT INTO users (profile) VALUES ( '{"name": "Tom", "email": "tom@example.com"}' );
MySQL also supports a native JSON
data type, allowing you to store, validate, and query JSON documents directly.
-- Creating a table with a JSON column CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, details JSON ); -- Inserting a JSON object INSERT INTO products (details) VALUES ( '{"name": "Laptop", "price": 1200}' );
You can query JSON columns using path expressions and operators. PostgreSQL uses ->
, ->>
, and #>
.
-- Querying JSON in PostgreSQL SELECT profile->>'name' AS username FROM users WHERE profile->>'email' = 'tom@example.com';
To improve performance, you can create indexes on JSON fields. PostgreSQL supports GIN indexes on jsonb
fields.
-- Creating GIN index on a JSONB column CREATE INDEX idx_profile ON users USING GIN (profile);
Modern databases allow converting JSON into relational format using functions like json_populate_record
or json_table
.
-- PostgreSQL: converting JSON to table format SELECT * FROM json_populate_record(NULL::users, '{"name":"Lily","age":22}');
JSON can be used in migration tools to seed databases with initial data, define schema structures, or manage version-controlled changes.
// JSON migration file (used by tools like Sequelize or Prisma) [ { "model": "User", "data": { "name": "Admin", "email": "admin@example.com" } } ]
JSON offers flexibility with dynamic structures, while relational models enforce strict schemas. Use JSON for unstructured or semi-structured data, and relational for structured data with strong relationships.
// JSON-style { "orderId": 101, "items": [ { "name": "Pen", "qty": 2 }, { "name": "Notebook", "qty": 1 } ] } // Relational-style Orders Table: | orderId | userId | |--------|--------| | 101 | 5 | OrderItems Table: | orderId | itemName | qty | |--------|-----------|-----| | 101 | Pen | 2 | | 101 | Notebook | 1 |
React applications commonly store JSON data in state using the `useState` hook. This allows dynamic rendering and updates based on JSON content.
// Using JSON in React state import React, { useState } from 'react'; function UserComponent() { const [user, setUser] = useState({ name: "Alice", age: 25 }); // Store JSON object in state return ( <div> <h3>Name: {user.name}</h3> <p>Age: {user.age}</p> </div> ); }
JSON can be passed as props to child components in frameworks like React, allowing flexible UI rendering based on structured data.
// Parent Component function App() { const data = { title: "Hello", message: "Welcome to JSON in React!" }; return <MessageCard info={data} />; } // Child Component function MessageCard({ info }) { return ( <div> <h2>{info.title}</h2> <p>{info.message}</p> </div> ); }
In Angular, JSON data can be bound to templates using the component class. This allows real-time updates and dynamic views using `{{ }}` syntax.
// app.component.ts export class AppComponent { user = { name: 'John', role: 'admin' }; // JSON object } // app.component.html <h3>Name: {{ user.name }}</h3> <p>Role: {{ user.role }}</p>
Vue uses reactive data binding with JSON objects stored in the `data()` method, allowing seamless UI updates.
// Vue component export default { data() { return { user: { name: "Lina", country: "Canada" } }; } } // In template <p>User: {{ user.name }} from {{ user.country }}</p>
Svelte uses reactive declarations, and JSON objects can be directly declared and used inside the component’s script section.
<script> let profile = { username: "dev_mj", email: "mj@example.com" }; </script> <p>Username: {profile.username}</p> <p>Email: {profile.email}</p>
You can use chart libraries like Chart.js or Recharts to visualize JSON data dynamically in graphs and dashboards.
// Using Chart.js with JSON const chartData = { labels: ["Jan", "Feb", "Mar"], datasets: [{ label: "Sales", data: [120, 190, 300], backgroundColor: "rgba(75, 192, 192, 0.2)" }] }; new Chart("myChart", { type: "bar", data: chartData });
Front-end frameworks can iterate over JSON arrays to populate elements like lists, tables, or cards dynamically.
// React example const products = [ { name: "Laptop", price: 899 }, { name: "Phone", price: 499 } ]; function ProductList() { return ( <ul> {products.map((item, index) => ( <li key={index}>{item.name} - ${item.price}</li> ))} </ul> ); }
Forms can be generated and validated using JSON schemas or config objects, allowing dynamic field creation and validation logic.
// Example of dynamic form field creation const fields = [ { label: "Name", type: "text", id: "name" }, { label: "Email", type: "email", id: "email" } ]; function DynamicForm() { return ( <form> {fields.map((field) => ( <div key={field.id}> <label>{field.label}</label> <input type={field.type} id={field.id} /> </div> ))} </form> ); }
One of the most common use cases in front-end frameworks is mapping through JSON arrays to render lists, cards, or tables.
// Vue example of mapping over JSON <template> <ul> <li v-for="(item, index) in items" :key="index"> {{ item }} </li> </ul> </template> <script> export default { data() { return { items: ["Apple", "Banana", "Orange"] }; } }; </script>
Modern front-end apps frequently fetch JSON from APIs and use that data in components for rendering or state management.
// React example using fetch API import React, { useEffect, useState } from 'react'; function ApiData() { const [userData, setUserData] = useState([]); useEffect(() => { fetch("https://jsonplaceholder.typicode.com/users") .then(res => res.json()) // Convert response to JSON .then(data => setUserData(data)); // Set JSON data in state }, []); return ( <ul> {userData.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }
A simple Todo list can store tasks as JSON objects, allowing you to add, delete, and mark tasks complete.
// Sample todos JSON array const todos = [ { id: 1, task: "Buy groceries", completed: false }, { id: 2, task: "Finish homework", completed: true } ]; // Example: Mark first todo complete todos[0].completed = true; console.log(todos);
Blog posts can be loaded from JSON arrays to dynamically display titles, authors, and content on a page.
// Blog posts JSON example const posts = [ { id: 1, title: "Intro to JSON", author: "Jane", content: "JSON is a lightweight format..." }, { id: 2, title: "Working with APIs", author: "Mark", content: "Fetching JSON data is simple..." } ]; // Display titles in console posts.forEach(post => { console.log(post.title + " by " + post.author); });
Product information like name, price, and description can be stored in JSON and used to build catalogs dynamically.
// Sample products JSON const products = [ { id: 101, name: "Laptop", price: 999, description: "High performance" }, { id: 102, name: "Headphones", price: 199, description: "Noise-cancelling" } ]; // Example: Display product names and prices products.forEach(p => { console.log(`${p.name} - $${p.price}`); });
Weather apps consume JSON responses from weather APIs to display current conditions and forecasts.
// Sample weather JSON response const weatherData = { "location": "New York", "temperature": 25, "condition": "Sunny" }; console.log(`Weather in ${weatherData.location}: ${weatherData.temperature}°C, ${weatherData.condition}`);
Messages in chat apps are often stored and transmitted as JSON objects containing sender info, message text, and timestamps.
// Sample chat message JSON const messages = [ { sender: "Alice", text: "Hello!", time: "10:00 AM" }, { sender: "Bob", text: "Hi there!", time: "10:01 AM" } ]; // Display chat messages messages.forEach(msg => { console.log(`[${msg.time}] ${msg.sender}: ${msg.text}`); });
Currency rates can be fetched as JSON from APIs and used to convert amounts between different currencies.
// Sample rates JSON const rates = { USD: 1, EUR: 0.85, GBP: 0.75 }; function convert(amount, from, to) { return (amount / rates[from]) * rates[to]; } console.log(convert(100, 'USD', 'EUR')); // Convert 100 USD to EUR
Contacts can be managed using JSON arrays storing names, phone numbers, and emails.
// Contacts JSON array const contacts = [ { name: "John Doe", phone: "123-4567", email: "john@example.com" }, { name: "Jane Smith", phone: "987-6543", email: "jane@example.com" } ]; // Example: List contact names contacts.forEach(contact => console.log(contact.name));
Movies with title, genre, and rating can be loaded from JSON for browsing and filtering.
// Movies JSON example const movies = [ { title: "Inception", genre: "Sci-Fi", rating: 8.8 }, { title: "The Godfather", genre: "Crime", rating: 9.2 } ]; // Display movie titles movies.forEach(movie => console.log(movie.title));
Quiz questions and answers can be stored in JSON, facilitating easy quiz rendering and evaluation.
// Quiz questions JSON const quiz = [ { question: "What is 2+2?", options: [3,4,5], answer: 4 }, { question: "Capital of France?", options: ["Paris", "Rome", "Berlin"], answer: "Paris" } ]; // Show questions and options quiz.forEach(q => { console.log(q.question); q.options.forEach(opt => console.log("- " + opt)); });
Portfolio projects can be stored as JSON objects and dynamically rendered on a website for easy updates.
// Portfolio projects JSON const projects = [ { name: "Website", description: "Personal portfolio", url: "https://example.com" }, { name: "App", description: "Mobile app", url: "https://app.example.com" } ]; // List project names and links projects.forEach(proj => { console.log(`${proj.name}: ${proj.url}`); });
Android apps use libraries like Gson or built-in JSON classes to parse and generate JSON data in Java or Kotlin.
// Java example: Parsing JSON using org.json String jsonString = "{\"name\":\"John\",\"age\":30}"; try { JSONObject obj = new JSONObject(jsonString); // Create JSON object String name = obj.getString("name"); // Get name value int age = obj.getInt("age"); // Get age value System.out.println("Name: " + name + ", Age: " + age); } catch (JSONException e) { e.printStackTrace(); // Handle parsing errors }
Swift uses Codable protocol or JSONSerialization for decoding and encoding JSON data in iOS apps.
// Swift example: Decoding JSON using Codable struct User: Codable { let name: String let age: Int } let jsonString = "{\"name\":\"Emma\",\"age\":25}" if let jsonData = jsonString.data(using: .utf8) { do { let user = try JSONDecoder().decode(User.self, from: jsonData) // Decode JSON print("Name: \(user.name), Age: \(user.age)") } catch { print("Error decoding JSON: \(error)") } }
React Native fetches JSON data over the network using the standard fetch API.
// Fetching JSON data in React Native fetch('https://api.example.com/user') .then(response => response.json()) // Parse JSON response .then(data => { console.log('User name:', data.name); }) .catch(error => { console.error('Error fetching JSON:', error); });
Flutter uses Dart's built-in JSON decoding with the dart:convert package to parse JSON into Dart objects.
import 'dart:convert'; void main() { String jsonString = '{"title": "Flutter", "version": 2}'; Mapdecoded = jsonDecode(jsonString); // Decode JSON string print('Title: ${decoded['title']}, Version: ${decoded['version']}'); }
Mobile apps use AsyncStorage (React Native) or SharedPreferences (Android) to persist JSON data locally as strings.
// React Native AsyncStorage example import AsyncStorage from '@react-native-async-storage/async-storage'; const storeUser = async () => { const user = {name: 'Jane', age: 28}; try { await AsyncStorage.setItem('user', JSON.stringify(user)); // Save JSON string } catch (e) { console.error('Failed to save user:', e); } }; const getUser = async () => { try { const jsonValue = await AsyncStorage.getItem('user'); const user = jsonValue != null ? JSON.parse(jsonValue) : null; // Parse stored JSON console.log(user); } catch (e) { console.error('Failed to load user:', e); } };
Mobile apps cache JSON API responses to improve performance and enable offline access, often using local storage or databases.
// Example: caching JSON response in React Native fetch('https://api.example.com/data') .then(res => res.json()) .then(async data => { await AsyncStorage.setItem('cachedData', JSON.stringify(data)); // Cache data console.log('Data cached'); });
Mobile developers often parse nested JSON objects or arrays, using recursive decoding or mapping to model classes.
// Example nested JSON parsing in Swift Codable struct Post: Codable { let id: Int let title: String let comments: [Comment] } struct Comment: Codable { let user: String let message: String } let jsonString = """ { "id": 1, "title": "Hello", "comments": [ {"user": "Alice", "message": "Nice post!"}, {"user": "Bob", "message": "Thanks for sharing."} ] } """ if let jsonData = jsonString.data(using: .utf8) { do { let post = try JSONDecoder().decode(Post.self, from: jsonData) print("Post title: \(post.title)") for comment in post.comments { print("Comment by \(comment.user): \(comment.message)") } } catch { print("Error decoding nested JSON: \(error)") } }
Apps use cached JSON data to provide functionality when offline, syncing with servers when the connection is restored.
// Pseudo code for offline mode if (networkAvailable()) { fetchDataFromServer().then(storeLocally); } else { loadDataFromLocalCache(); }
Push notifications often include JSON payloads to define message content, actions, and metadata.
// Example Firebase push notification JSON payload { "to": "device_token", "notification": { "title": "New Message", "body": "You have a new message" }, "data": { "conversation_id": "1234" } }
Proper error handling prevents crashes due to malformed JSON by catching parsing exceptions and fallback logic.
// Java example catching JSONException try { JSONObject obj = new JSONObject(invalidJsonString); } catch (JSONException e) { e.printStackTrace(); // Show user error or fallback }
JSON data can be nested multiple levels deep, representing complex hierarchical information like user profiles or organizational charts.
// Example of deeply nested JSON const data = { user: { id: 1, profile: { name: "Alice", contacts: { email: "alice@example.com", phones: ["123-4567", "789-0123"] } } } }; console.log(data.user.profile.contacts.email); // Access nested email
Flattening converts nested JSON into a single-level object with dot-separated keys, useful for easier querying or CSV export.
// Function to flatten JSON function flatten(obj, prefix = '', res = {}) { for (const key in obj) { const val = obj[key]; const newKey = prefix ? `${prefix}.${key}` : key; if (typeof val === 'object' && val !== null && !Array.isArray(val)) { flatten(val, newKey, res); } else { res[newKey] = val; } } return res; } const nested = { a: { b: { c: 1 } }, d: 2 }; const flat = flatten(nested); console.log(flat); // { 'a.b.c': 1, d: 2 }
Multiple JSON objects can be merged to combine properties, useful in configuration merging or data aggregation.
// Merge two JSON objects const obj1 = { name: "Alice", age: 25 }; const obj2 = { age: 30, city: "New York" }; const merged = { ...obj1, ...obj2 }; console.log(merged); // { name: "Alice", age: 30, city: "New York" }
You can filter arrays of JSON objects based on property values to find matching items.
// Filter users older than 25 const users = [ { name: "John", age: 20 }, { name: "Jane", age: 30 }, { name: "Jim", age: 27 } ]; const filtered = users.filter(user => user.age > 25); console.log(filtered); // [{name: "Jane", age:30}, {name: "Jim", age:27}]
Reduce helps aggregate values from JSON arrays, such as summing amounts or counting occurrences.
// Sum ages of users const users = [ { name: "John", age: 20 }, { name: "Jane", age: 30 } ]; const totalAge = users.reduce((sum, user) => sum + user.age, 0); console.log(totalAge); // 50
You can capture form inputs and convert them into JSON for submission or storage.
// Example function to create JSON from form inputs function formToJSON(form) { const data = {}; new FormData(form).forEach((value, key) => { data[key] = value; }); return data; } // Usage: pass HTMLFormElement to formToJSON to get JSON object
Access JSON properties dynamically using variables holding the key names.
// Dynamic key access const obj = { name: "Alice", age: 25 }; const key = "age"; console.log(obj[key]); // 25
You can customize JSON serialization using replacer functions to control which properties are included or transformed.
// Using replacer in JSON.stringify const obj = { name: "Alice", age: 25, password: "secret" }; const json = JSON.stringify(obj, (key, value) => { if (key === "password") return undefined; // Exclude password return value; }); console.log(json); // {"name":"Alice","age":25}
Objects can define their own `toJSON` method to control how they serialize to JSON.
// Custom toJSON method example const user = { name: "Bob", password: "hidden", toJSON() { return { name: this.name }; // Only include name when serialized } }; console.log(JSON.stringify(user)); // {"name":"Bob"}
Efficiently managing JSON size and structure can reduce memory use, like removing unused fields or compressing strings.
// Example: Remove null or undefined values to reduce size function cleanJSON(obj) { return JSON.parse(JSON.stringify(obj, (k, v) => (v == null ? undefined : v))); } const largeData = { a: 1, b: null, c: undefined }; const cleaned = cleanJSON(largeData); console.log(cleaned); // { a: 1 }
AI APIs commonly accept JSON-formatted requests and return JSON responses, making JSON the lingua franca for AI service communication.
// Example: AI API request payload in JSON format { "model": "gpt-4", "prompt": "Explain JSON in simple terms.", "max_tokens": 100 }
OpenAI’s API uses JSON for both sending prompts and receiving generated text, enabling easy integration across platforms.
POST /v1/chat/completions Content-Type: application/json { "model": "gpt-4", "messages": [ {"role": "user", "content": "What is JSON?"} ], "max_tokens": 50 } // Response is JSON: { "id": "chatcmpl-abc123", "choices": [ { "message": { "role": "assistant", "content": "JSON is a lightweight data format..." } } ] }
Prompts and responses in AI APIs are structured in JSON to maintain context, roles, and content in a readable way.
// Structured prompt example for chat-based AI { "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Tell me about JSON."} ] }
AI platforms may send event notifications via webhooks with JSON payloads for asynchronous updates like job completion or errors.
// Example webhook JSON payload when AI task completes { "event": "job_completed", "job_id": "12345", "result_url": "https://api.example.com/results/12345" }
Image recognition APIs return JSON data describing detected objects, labels, or confidence scores.
// Example image recognition response { "objects": [ {"name": "cat", "confidence": 0.98}, {"name": "sofa", "confidence": 0.88} ] }
NLU APIs return JSON with analyzed intents, entities, and sentiment to help applications understand human language.
// Sample NLU API response JSON { "intent": "book_flight", "entities": { "destination": "Paris", "date": "2025-07-20" }, "sentiment": "positive" }
Speech recognition services accept audio data and return recognized text wrapped in JSON for easy consumption.
// Speech-to-text API response example { "transcript": "Hello, how are you?", "confidence": 0.95 }
Sentiment analysis APIs receive text in JSON format and respond with sentiment scores or labels.
// Request example { "text": "I love using JSON for APIs!" } // Response example { "sentiment": "positive", "score": 0.92 }
APIs communicate rate limits and errors using JSON, enabling clients to parse and handle responses programmatically.
// Rate limit error response example { "error": { "code": 429, "message": "Too many requests. Please wait and retry." } }
Developers can integrate several AI services by exchanging JSON between them, orchestrating complex workflows.
// Example combining text generation and sentiment analysis let generatedText = { "content": "JSON is a lightweight data format." }; let sentimentRequest = { "text": generatedText.content }; // Send sentimentRequest JSON to sentiment API for analysis
JSON config files are used to define AI pipeline parameters, making workflows reproducible and easy to adjust.
// Example JSON config for an AI pipeline { "pipeline_name": "ImageClassification", "batch_size": 64, "learning_rate": 0.001, "epochs": 20, "data_path": "/data/images" }
TensorFlow Serving uses JSON to format prediction requests and responses in REST APIs.
// Sample prediction request JSON for TensorFlow Serving { "signature_name": "serving_default", "instances": [ {"input_image": [0.0, 1.2, 0.3, ...]} ] }
ONNX models often include JSON metadata to describe model info, inputs, and outputs.
// Simplified JSON metadata example for ONNX model { "model_name": "resnet50", "input_shape": [1, 3, 224, 224], "output_labels": ["cat", "dog", "bird"] }
Model hyperparameters and settings can be stored in JSON for easy loading and reproducibility.
{ "optimizer": "adam", "dropout_rate": 0.5, "activation": "relu" }
MLFlow and Kubeflow use JSON for experiment tracking, parameter storage, and metadata sharing.
// Example MLFlow params JSON { "experiment_id": "12345", "run_id": "67890", "parameters": { "learning_rate": 0.01, "batch_size": 32 } }
Inference results and logs are stored in JSON format to enable easy analysis and monitoring.
{ "timestamp": "2025-07-18T10:00:00Z", "model_version": "v1.2", "input_data": {...}, "prediction": "cat", "confidence": 0.95 }
Preprocessing steps and parameters are often stored in JSON for consistency and pipeline automation.
{ "resize": [224, 224], "normalize_mean": [0.485, 0.456, 0.406], "normalize_std": [0.229, 0.224, 0.225] }
Chatbots use JSON to structure dialogue flows, intents, and entity recognition data.
{ "intents": [ { "name": "greeting", "examples": ["Hi", "Hello", "Hey"], "responses": ["Hello! How can I help?"] } ] }
JSON is stricter and widely supported, while YAML is more readable but can be error-prone. Both are used in deployment configs.
// JSON example { "replicas": 3, "image": "ai-model:latest" } // Equivalent YAML replicas: 3 image: ai-model:latest
Real-time inference APIs receive JSON payloads containing input data and return predictions in JSON format.
// Request payload { "input": [0.5, 0.8, 0.3, ...] } // Response payload { "prediction": "dog", "probability": 0.87 }
JSON security involves protecting JSON data from attacks and ensuring safe data exchange between clients and servers.
// Always validate and sanitize JSON data to prevent security issues const userInput = '{"name": "Alice"}'; // Example JSON input from user try { const data = JSON.parse(userInput); // Parse JSON safely console.log(data.name); // Use data carefully } catch(e) { console.error("Invalid JSON input"); }
Attackers inject malicious JSON or manipulate JSON inputs to alter application behavior or access unauthorized data.
// Unsafe example vulnerable to JSON injection let unsafeData = '{"role":"user"}'; let parsed = JSON.parse(unsafeData); // If attacker changes role to "admin", unauthorized access could occur // Always validate roles and other critical fields after parsing if(parsed.role !== "admin" && parsed.role !== "user") { throw new Error("Invalid role detected"); }
XSS attacks can occur if JSON data containing scripts is directly injected into web pages without escaping.
// Vulnerable example inserting JSON data into HTML let jsonData = '{"comment":"<script>alert(1)</script>"}'; let parsed = JSON.parse(jsonData); document.getElementById("comments").innerHTML = parsed.comment; // Dangerous! // Safer approach: use textContent or sanitize input document.getElementById("comments").textContent = parsed.comment; // Prevents script execution
Validate JSON input schema and content to prevent malformed or malicious data entering your system.
// Using a simple schema validation example function validateUser(user) { if(typeof user.name !== "string" || user.name.length === 0) return false; if(typeof user.age !== "number" || user.age < 0) return false; return true; } const input = JSON.parse('{"name":"Bob","age":25}'); if(!validateUser(input)) { throw new Error("Invalid user data"); }
Before sending JSON data to clients, sanitize outputs to avoid leaking sensitive information or enabling XSS.
// Remove sensitive fields before sending JSON const user = { id: 1, name: "Alice", password: "secret123" // Sensitive, should be removed }; function sanitizeUser(user) { const sanitized = {...user}; delete sanitized.password; // Remove password return sanitized; } console.log(JSON.stringify(sanitizeUser(user))); // Safe to send
CORS (Cross-Origin Resource Sharing) policies control which domains can access your JSON APIs, preventing unauthorized cross-origin requests.
// Example CORS header in Express.js app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "https://trustedwebsite.com"); res.header("Access-Control-Allow-Methods", "GET,POST"); next(); });
JSON data stored on disk or in databases should be protected with encryption and access controls.
// Example: Encrypt JSON data before storage (Node.js using crypto) const crypto = require('crypto'); const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); function encrypt(jsonData) { const cipher = crypto.createCipheriv(algorithm, key, iv); let encrypted = cipher.update(JSON.stringify(jsonData), 'utf8', 'hex'); encrypted += cipher.final('hex'); return encrypted; } const data = { secret: "top-secret info" }; const encryptedData = encrypt(data); console.log(encryptedData); // Encrypted JSON string
JWTs use JSON to securely transmit claims between parties and include signature verification to ensure integrity.
// Example JWT payload decoded (not the full token) { "sub": "1234567890", "name": "Majid", "iat": 1516239022 // Issued at timestamp } // JWTs are signed and verified using secret keys or certificates
Encrypting JSON payloads protects sensitive data during transmission, especially in untrusted networks.
// Example: Encrypt JSON before sending (simplified) const message = { secret: "encrypt this" }; const encryptedMessage = encrypt(message); // Use encryption function from earlier fetch("/api/secure", { method: "POST", body: encryptedMessage, // Send encrypted data headers: { "Content-Type": "application/octet-stream" } });
Audit logs often store JSON records to track changes and access, allowing easy querying and structured logging.
// Example JSON audit log entry { "timestamp": "2025-07-18T10:00:00Z", "user": "majid_dev", "action": "login", "success": true, "ip": "192.168.1.10" } // Storing logs in JSON format aids analysis and debugging
Many applications use config.json
files to store configuration settings in JSON format, making configs easy to read and update.
// Example config.json { "port": 8080, // Server port "dbHost": "localhost", // Database host "debugMode": true // Debug flag }
Applications load JSON configs at runtime to customize behavior without changing code.
// Loading config.json in Node.js const fs = require('fs'); const config = JSON.parse(fs.readFileSync('config.json', 'utf8')); console.log("Server running on port:", config.port);
Docker Compose primarily uses YAML, but JSON can be used with Docker CLI for configuration and automation.
// Example JSON snippet to create a container via Docker CLI { "Image": "nginx", "ExposedPorts": { "80/tcp": {} }, "HostConfig": { "PortBindings": { "80/tcp": [{ "HostPort": "8080" }] } } }
CI/CD tools use JSON for pipeline definitions, triggering builds, and managing automation workflows.
// Example: JSON payload triggering a CI build (simplified) { "branch": "main", "commit": "a1b2c3d4", "build": true }
GitHub Actions uses YAML but often deals with JSON outputs and inputs for workflows and actions.
// GitHub Action step reading JSON output (pseudo-code) steps: - name: Get JSON output id: jsondata run: echo '{ "result": "success" }' > output.json - name: Use JSON output run: | RESULT=$(jq -r '.result' output.json) echo "Build result: $RESULT" # jq is used to parse JSON in bash scripts
npm uses package.json
to manage project metadata, dependencies, scripts, and more.
// Sample package.json snippet { "name": "my-app", "version": "1.0.0", "scripts": { "start": "node index.js", "test": "jest" }, "dependencies": { "express": "^4.18.1" } }
Scripts often read JSON files to automate tasks such as builds, deployments, or environment setup.
// Node.js script reading JSON to automate deployment const fs = require('fs'); const deploymentConfig = JSON.parse(fs.readFileSync('deploy.json', 'utf8')); if(deploymentConfig.deploy) { console.log("Starting deployment to:", deploymentConfig.server); // Add deployment logic here }
ESLint and Babel use JSON-based config files (.eslintrc.json
, babel.config.json
) to specify rules and plugins.
// .eslintrc.json example { "env": { "browser": true, "node": true }, "rules": { "no-console": "warn", "semi": ["error", "always"] } }
Test frameworks sometimes load JSON files with test inputs and expected outputs for automated testing.
// Example testCases.json [ { "input": 5, "expected": 25 }, { "input": 10, "expected": 100 } ]
JSON files store environment variables and settings that can be switched between development, staging, and production environments.
// env.json example { "development": { "apiUrl": "http://localhost:3000/api", "debug": true }, "production": { "apiUrl": "https://api.example.com", "debug": false } }
AWS services like Lambda, API Gateway, and IAM extensively use JSON for configurations, policies, and event data.
// Example IAM policy in JSON granting read-only S3 access { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::example-bucket/*"] } ] }
Azure DevOps uses JSON for task definitions, build artifacts, and REST API interactions.
// Example JSON for a build artifact metadata in Azure Pipelines { "artifactName": "drop", "type": "Container", "url": "https://dev.azure.com/project/_apis/build/builds/123/artifacts" }
Google Cloud Platform exposes many REST APIs that send and receive JSON payloads for managing resources.
// Example Google Cloud API response (VM instance details) { "name": "instance-1", "zone": "us-central1-a", "status": "RUNNING", "machineType": "n1-standard-1" }
Terraform and AWS CloudFormation use JSON or YAML files to define infrastructure as code (IaC).
// CloudFormation JSON example creating an S3 bucket { "Resources": { "MyBucket": { "Type": "AWS::S3::Bucket", "Properties": { "BucketName": "my-example-bucket" } } } }
AWS CloudWatch can ingest and parse JSON-formatted logs, enabling structured log analysis.
// Example JSON log entry { "timestamp": "2025-07-18T10:00:00Z", "level": "ERROR", "message": "Failed to connect to database", "requestId": "abc123" }
IAM policies are written in JSON to define permissions for AWS resources securely and granularly.
// IAM policy allowing Lambda invocation { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:us-east-1:123456789012:function:my-function" }] }
Google Cloud AI Platform uses JSON to define models, jobs, and prediction requests.
// JSON request to submit a training job { "jobId": "my-training-job", "trainingInput": { "scaleTier": "BASIC", "packageUris": ["gs://bucket/path/trainer.tar.gz"], "pythonModule": "trainer.task", "region": "us-central1" } }
Kubernetes supports JSON manifests (as well as YAML) to describe resources like Pods, Services, and Deployments.
// Kubernetes Pod manifest in JSON { "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "nginx-pod" }, "spec": { "containers": [{ "name": "nginx", "image": "nginx:latest" }] } }
Secrets are often stored or transmitted as JSON objects, usually encrypted or managed with secret managers.
// Example JSON secret object (encrypted or base64 encoded in practice) { "username": "admin", "password": "P@ssw0rd!" }
Monitoring tools collect metrics and logs in JSON format for analysis, alerting, and dashboards.
// Sample JSON metric record { "metricName": "CPUUtilization", "value": 75, "unit": "Percent", "timestamp": "2025-07-18T10:05:00Z" }
GraphQL is a query language for APIs that lets clients request exactly the data they need, while traditional JSON APIs usually return fixed data structures.
// Typical JSON REST API response { "id": 1, "name": "Alice", "email": "alice@example.com", "posts": [ /* full list of posts included */ ] } // GraphQL query specifying needed fields query { user(id: 1) { name posts { title } } }
You can transform JSON data to fit GraphQL schema structures to optimize queries and responses.
// Sample JSON { "id": 1, "name": "Alice", "posts": [ {"title": "Post 1", "content": "Content 1"}, {"title": "Post 2", "content": "Content 2"} ] } // GraphQL schema representation (simplified) type User { id: ID name: String posts: [Post] } type Post { title: String content: String }
gRPC mainly uses Protobuf for serialization but can work with JSON for debugging or REST gateways.
// Example: JSON payload sent via REST proxy for gRPC service { "userId": 123, "action": "getProfile" } // The gRPC server will convert between Protobuf and JSON formats
Protobuf is a compact, binary serialization format, faster and smaller than JSON but less human-readable.
// JSON example (human-readable) { "id": 1, "name": "Alice" } // Protobuf (binary, not readable) encoded from above JSON // More compact and efficient for network transmission
JSON data can be converted to CSV format for spreadsheets or tabular data processing.
// JSON array of objects [ { "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 } ] // Converted CSV // name,age // Alice,30 // Bob,25
JSON can be mapped to XML for interoperability with systems requiring XML.
// JSON example { "note": { "to": "Bob", "message": "Hello" } } // Equivalent XML <note> <to>Bob</to> <message>Hello</message> </note>
YAML is a human-friendly data format often converted to/from JSON for configuration and data exchange.
// YAML example note: to: Bob message: Hello // Equivalent JSON { "note": { "to": "Bob", "message": "Hello" } }
Formats like BSON and MessagePack encode JSON data in binary form to improve speed and reduce size.
// BSON example used by MongoDB stores JSON-like documents in binary // MessagePack example is a compact binary JSON serialization // These formats are faster to parse but not human-readable
Tools and libraries allow converting data between JSON, XML, CSV, YAML, and binary JSON formats to integrate diverse systems.
// Example using Node.js 'xml2js' to convert XML to JSON const xml2js = require('xml2js'); const xml = '<note><to>Bob</to></note>'; xml2js.parseString(xml, (err, result) => { console.log(result); // JSON output of the XML });
jq
is a powerful command-line tool to query, filter, and transform JSON data.
// Extract 'name' from JSON file using jq jq '.name' data.json // Convert JSON array to CSV jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @csv' data.json
Online JSON validators help you check if your JSON is valid and properly formatted.
// Example: Paste JSON in an online validator like https://jsonlint.com/ // It will highlight syntax errors and formatting issues { "name": "Majid", "age": 28 }
JSON formatter tools prettify JSON data by adding indentation and line breaks for readability.
// Example: Using online JSON formatter or VSCode's built-in formatter // Original JSON (minified) {"name":"Alice","city":"Toronto"} // Formatted JSON { "name": "Alice", "city": "Toronto" }
Postman is a powerful GUI tool to test, debug, and document JSON APIs.
// Example: Sending a POST request with JSON body in Postman /* POST https://api.example.com/users Headers: Content-Type: application/json Body: { "username": "majid_dev", "email": "majid@example.com" } */
Insomnia is another REST client similar to Postman, with support for JSON testing and environment variables.
// Example: Using Insomnia to test API endpoints // Define environment variables for API URL and authorization tokens // Send JSON requests and view formatted JSON responses
jq is a command-line JSON processor that filters, transforms, and queries JSON data.
// Using jq to extract the "name" field from JSON file cat users.json | jq '.name' // Filter users with age > 25 cat users.json | jq 'map(select(.age > 25))'
JSONPath is a syntax to query and filter parts of a JSON document, similar to XPath for XML.
// Example JSONPath expression to get all names $.users[*].name // Using tools or libraries to execute JSONPath queries on JSON data
JSON tree viewers display nested JSON data as expandable/collapsible nodes for easier exploration.
// Tools like JSON Viewer Chrome Extension or online JSON tree viewers // You can load JSON and explore nested structures interactively
Online JSON editors let you create, edit, and validate JSON visually with helpful features like syntax highlighting.
// Example: Using https://jsoneditoronline.org/ // Load JSON, edit structure, and export formatted output
VSCode extensions enhance JSON editing with features like schema validation, auto-completion, and formatting.
// Popular extensions: // - JSON Tools // - Prettier (for formatting) // - JSON Schema Validator // Example: VSCode auto-completes keys based on JSON schemas
You can build custom JSON parsers, formatters, or validators using languages like JavaScript or Python.
// Simple JSON pretty printer in JavaScript function prettyPrintJSON(jsonString) { try { const obj = JSON.parse(jsonString); return JSON.stringify(obj, null, 2); // 2-space indentation } catch(e) { return "Invalid JSON: " + e.message; } } // Usage: const uglyJSON = '{"name":"Alice","age":30}'; console.log(prettyPrintJSON(uglyJSON));
Fetch weather data from a JSON-based API and display current weather conditions dynamically on a dashboard.
// Fetch weather JSON from API and display temperature fetch('https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=Toronto') .then(res => res.json()) .then(data => { console.log("Temperature:", data.current.temp_c, "°C"); document.getElementById('temp').textContent = data.current.temp_c + " °C"; });
Use JSON files to simulate products, orders, and user data in a backend for an e-commerce app.
// Sample products JSON [ { "id": 1, "name": "Laptop", "price": 899.99 }, { "id": 2, "name": "Phone", "price": 499.99 } ] // Example: Load products and display const products = require('./products.json'); products.forEach(p => console.log(p.name + ": $" + p.price));
Manage students, classes, and attendance records stored in JSON to simplify data management.
// Example JSON student record { "students": [ { "id": 101, "name": "Alice", "attendance": 95 }, { "id": 102, "name": "Bob", "attendance": 87 } ] }
Store blog posts as JSON objects and render them dynamically on a website.
// Example blog post JSON { "id": 1, "title": "Introduction to JSON", "content": "JSON stands for JavaScript Object Notation..." }
Keep track of income and expenses using JSON reports to analyze personal finances.
// Example finance record JSON { "transactions": [ { "date": "2025-07-01", "amount": -50, "category": "Groceries" }, { "date": "2025-07-03", "amount": 2000, "category": "Salary" } ] }
Use JSON configuration and data files to build a chatbot that responds based on structured JSON data.
// Sample bot responses in JSON { "greetings": ["Hello!", "Hi there!", "Greetings!"], "farewell": ["Goodbye!", "See you later!"] }
Send and receive JSON messages over WebSocket connections to build real-time chat applications.
// Sending JSON message over WebSocket const socket = new WebSocket('wss://chat.example.com'); socket.onopen = () => { socket.send(JSON.stringify({ type: 'message', text: 'Hello everyone!' })); }; socket.onmessage = (event) => { const msg = JSON.parse(event.data); console.log('Received:', msg.text); };
Manage flights, hotels, and bookings using JSON data for a travel booking web interface.
// Sample booking JSON { "flights": [ { "flightNumber": "AC101", "departure": "Toronto", "arrival": "NYC" } ], "hotels": [ { "name": "Grand Hotel", "city": "NYC", "pricePerNight": 150 } ] }
Visualize patient records stored in JSON format securely on a web interface.
// Patient record JSON { "patientId": 555, "name": "John Doe", "conditions": ["Diabetes", "Hypertension"], "medications": [ { "name": "Metformin", "dosage": "500mg" } ] }
Build a simple content management system that stores all data in JSON files for easy editing and rendering.
// CMS content stored as JSON pages { "pages": [ { "slug": "home", "title": "Welcome", "content": "Welcome to our site!" }, { "slug": "about", "title": "About Us", "content": "We build JSON apps." } ] }