JSON (Native)
Library
JSON (Native)
Overview
JSON (JavaScript Object Notation) is a lightweight data exchange format provided as JavaScript's standard serialization feature. With a simple API using JSON.stringify() and JSON.parse(), it converts JavaScript objects to JSON strings and vice versa. Available natively in all JavaScript environments without requiring external libraries, it is the most widely used standard for data exchange in web applications and APIs.
Details
JSON Native was standardized as part of ECMAScript 5 specification and is now natively supported by all modern browsers and Node.js. It serves various purposes including HTTP communication, file storage, and configuration files with its highly readable text format. Despite its simple API, it offers flexible output control through replacer functions and space arguments, and customized parsing through reviver functions.
Key Features
- Native Support: No additional libraries required in any JavaScript environment
- Lightweight: Zero overhead with high-speed operation
- Readability: Human-readable text format
- Compatibility: High compatibility across multiple languages and platforms
- Flexibility: Customizable conversion processing through replacer/reviver functions
- Web Standard: De facto standard for RESTful APIs and web applications
Pros and Cons
Pros
- No external libraries needed in JavaScript environments (0KB bundle size)
- Low learning curve with intuitive API design
- Excellent compatibility across multiple languages and platforms
- Human-readable and writable text format
- High affinity with HTTP protocol
- Easy debugging and log output
Cons
- Cannot efficiently represent binary data
- Cannot handle circular reference objects
- No standard support for JavaScript-specific types like Date or functions
- Larger file size compared to binary formats
- Security risk of JSON injection attacks
- Performance constraints with large data volumes
Reference Pages
Code Examples
Basic Serialization
// Basic object conversion
const userObject = {
id: 123,
name: 'John Doe',
email: '[email protected]',
isActive: true,
lastLogin: null
};
// Convert object to JSON string
const jsonString = JSON.stringify(userObject);
console.log(jsonString);
// Output: {"id":123,"name":"John Doe","email":"[email protected]","isActive":true,"lastLogin":null}
// Convert JSON string to object
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject);
// Output: { id: 123, name: 'John Doe', email: '[email protected]', isActive: true, lastLogin: null }
// Array conversion
const numbersArray = [1, 2, 3, 4, 5];
const arrayJson = JSON.stringify(numbersArray);
console.log(arrayJson); // Output: "[1,2,3,4,5]"
const parsedArray = JSON.parse(arrayJson);
console.log(parsedArray); // Output: [1, 2, 3, 4, 5]
Advanced Configuration and Customization
// Output control using replacer function
const sensitiveData = {
username: 'user123',
password: 'secret123',
email: '[email protected]',
apiKey: 'api_key_secret',
publicInfo: 'this is public'
};
// Replacer function to exclude sensitive information
function secureReplacer(key, value) {
// Exclude password and API key
if (key === 'password' || key === 'apiKey') {
return undefined;
}
return value;
}
const secureJson = JSON.stringify(sensitiveData, secureReplacer);
console.log(secureJson);
// Output: {"username":"user123","email":"[email protected]","publicInfo":"this is public"}
// Include only specific properties
const allowedKeys = ['username', 'email'];
const filteredJson = JSON.stringify(sensitiveData, allowedKeys);
console.log(filteredJson);
// Output: {"username":"user123","email":"[email protected]"}
// Formatted output (space argument)
const prettyJson = JSON.stringify(userObject, null, 2);
console.log(prettyJson);
/*
{
"id": 123,
"name": "John Doe",
"email": "[email protected]",
"isActive": true,
"lastLogin": null
}
*/
// Conversion during parsing using reviver function
const dateJson = '{"name":"John","created":"2025-01-01T00:00:00.000Z","count":"42"}';
function dateReviver(key, value) {
// Convert ISO date strings to Date objects
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/.test(value)) {
return new Date(value);
}
// Convert numeric strings to numbers
if (key === 'count' && typeof value === 'string' && !isNaN(value)) {
return parseInt(value, 10);
}
return value;
}
const revivedObject = JSON.parse(dateJson, dateReviver);
console.log(revivedObject);
// Output: { name: 'John', created: 2025-01-01T00:00:00.000Z, count: 42 }
console.log(revivedObject.created instanceof Date); // true
Performance Optimization
// Efficient processing of large data volumes
function createLargeData(size) {
const data = [];
for (let i = 0; i < size; i++) {
data.push({
id: i,
name: `user_${i}`,
value: Math.random(),
timestamp: Date.now()
});
}
return data;
}
// Performance measurement function
function measurePerformance(label, fn) {
const start = performance.now();
const result = fn();
const end = performance.now();
console.log(`${label}: ${(end - start).toFixed(2)}ms`);
return result;
}
// Processing measurement for large data
const largeData = createLargeData(10000);
const jsonString = measurePerformance('Stringify 10,000 objects', () => {
return JSON.stringify(largeData);
});
const parsedData = measurePerformance('Parse large JSON', () => {
return JSON.parse(jsonString);
});
console.log(`JSON size: ${(jsonString.length / 1024).toFixed(2)} KB`);
// Chunk processing for large data volumes
function processInChunks(data, chunkSize = 1000) {
const chunks = [];
for (let i = 0; i < data.length; i += chunkSize) {
const chunk = data.slice(i, i + chunkSize);
chunks.push(JSON.stringify(chunk));
}
return chunks;
}
const chunks = measurePerformance('Chunk processing', () => {
return processInChunks(largeData);
});
console.log(`Processed ${chunks.length} chunks`);
Type Safety and Validation
// JSON schema-like validation
function validateUserObject(obj) {
const requiredFields = ['id', 'name', 'email'];
const errors = [];
// Required field validation
for (const field of requiredFields) {
if (!(field in obj)) {
errors.push(`Missing required field: ${field}`);
}
}
// Type validation
if (typeof obj.id !== 'number') {
errors.push('id must be a number');
}
if (typeof obj.name !== 'string') {
errors.push('name must be a string');
}
if (typeof obj.email !== 'string' || !obj.email.includes('@')) {
errors.push('email must be a valid email string');
}
return {
isValid: errors.length === 0,
errors
};
}
// Safe JSON parsing function
function safeJsonParse(jsonString, validator = null) {
try {
const parsed = JSON.parse(jsonString);
if (validator) {
const validation = validator(parsed);
if (!validation.isValid) {
throw new Error(`Validation failed: ${validation.errors.join(', ')}`);
}
}
return { success: true, data: parsed };
} catch (error) {
return { success: false, error: error.message };
}
}
// Usage examples
const validJson = '{"id":123,"name":"John Doe","email":"[email protected]"}';
const invalidJson = '{"name":"John Doe","email":"invalid-email"}';
const validResult = safeJsonParse(validJson, validateUserObject);
console.log('Valid result:', validResult);
const invalidResult = safeJsonParse(invalidJson, validateUserObject);
console.log('Invalid result:', invalidResult);
// TypeScript-style type checking (runtime)
function isUserType(obj) {
return (
typeof obj === 'object' &&
obj !== null &&
typeof obj.id === 'number' &&
typeof obj.name === 'string' &&
typeof obj.email === 'string'
);
}
function parseUserJson(jsonString) {
const result = safeJsonParse(jsonString);
if (result.success && isUserType(result.data)) {
return result.data;
}
throw new Error('Invalid user JSON format');
}
Error Handling
// Robust JSON parsing processing
function robustJsonParse(input, options = {}) {
const {
fallback = null,
logErrors = false,
attemptRepair = false
} = options;
// Input validation
if (typeof input !== 'string') {
if (logErrors) console.error('Input is not a string:', typeof input);
return fallback;
}
if (input.trim() === '') {
if (logErrors) console.error('Input is empty string');
return fallback;
}
try {
return JSON.parse(input);
} catch (error) {
if (logErrors) {
console.error('JSON parse error:', {
message: error.message,
input: input.substring(0, 100) + (input.length > 100 ? '...' : ''),
position: error.message.match(/position (\d+)/)?.[1]
});
}
// Attempt automatic repair
if (attemptRepair) {
try {
// Remove trailing commas
let repairedInput = input.replace(/,(\s*[}\]])/g, '$1');
// Fix invalid quotes
repairedInput = repairedInput.replace(/'/g, '"');
const repaired = JSON.parse(repairedInput);
if (logErrors) console.log('JSON repair successful');
return repaired;
} catch (repairError) {
if (logErrors) console.error('JSON repair failed:', repairError.message);
}
}
return fallback;
}
}
// Usage example
const malformedJson = `{
"name": "Test",
"items": [1, 2, 3,],
"active": true,
}`;
const result = robustJsonParse(malformedJson, {
fallback: {},
logErrors: true,
attemptRepair: true
});
console.log('Parsed result:', result);
// Streaming JSON parser (for large files)
function parseJsonStream(jsonString, onObject, onError) {
let depth = 0;
let currentObject = '';
let inString = false;
let escaped = false;
for (let i = 0; i < jsonString.length; i++) {
const char = jsonString[i];
currentObject += char;
if (!inString) {
if (char === '{' || char === '[') {
depth++;
} else if (char === '}' || char === ']') {
depth--;
if (depth === 0) {
// Found complete object
try {
const obj = JSON.parse(currentObject);
onObject(obj);
currentObject = '';
} catch (error) {
onError(error, currentObject);
}
}
}
}
if (char === '"' && !escaped) {
inString = !inString;
}
escaped = char === '\\' && !escaped;
}
}
// Streaming parser usage example
const streamData = '{"id":1,"name":"A"}{"id":2,"name":"B"}{"id":3,"name":"C"}';
const objects = [];
parseJsonStream(streamData,
(obj) => objects.push(obj),
(error, content) => console.error('Parse error:', error.message, content)
);
console.log('Streamed objects:', objects);
Web API Integration
// Fetch API and JSON integration
class ApiClient {
constructor(baseUrl) {
this.baseUrl = baseUrl;
this.defaultHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
}
async request(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const config = {
headers: { ...this.defaultHeaders, ...options.headers },
...options
};
// JSON serialization of request body
if (config.body && typeof config.body === 'object') {
config.body = JSON.stringify(config.body);
}
try {
const response = await fetch(url, config);
// Check response headers
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error(`Unexpected content type: ${contentType}`);
}
const data = await response.json();
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${data.message || 'Request failed'}`);
}
return data;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
async get(endpoint) {
return this.request(endpoint, { method: 'GET' });
}
async post(endpoint, data) {
return this.request(endpoint, {
method: 'POST',
body: data
});
}
async put(endpoint, data) {
return this.request(endpoint, {
method: 'PUT',
body: data
});
}
async delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
}
// API client usage example
const api = new ApiClient('https://api.example.com');
async function manageUsers() {
try {
// Get user list
const users = await api.get('/users');
console.log('Users:', users);
// Create new user
const newUser = {
name: 'Jane Smith',
email: '[email protected]',
department: 'Development'
};
const createdUser = await api.post('/users', newUser);
console.log('Created user:', createdUser);
// Update user information
const updatedUser = await api.put(`/users/${createdUser.id}`, {
...createdUser,
department: 'Planning'
});
console.log('Updated user:', updatedUser);
} catch (error) {
console.error('User management failed:', error);
}
}
// WebSocket and JSON integration
class JsonWebSocketClient {
constructor(url) {
this.url = url;
this.ws = null;
this.messageHandlers = new Map();
}
connect() {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('WebSocket connected');
resolve();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
reject(error);
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.handleMessage(data);
} catch (error) {
console.error('Failed to parse WebSocket message:', error);
}
};
});
}
send(type, payload) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
const message = {
type,
payload,
timestamp: Date.now()
};
this.ws.send(JSON.stringify(message));
}
}
on(messageType, handler) {
this.messageHandlers.set(messageType, handler);
}
handleMessage(data) {
const handler = this.messageHandlers.get(data.type);
if (handler) {
handler(data.payload);
}
}
disconnect() {
if (this.ws) {
this.ws.close();
}
}
}
// WebSocket client usage example
const wsClient = new JsonWebSocketClient('wss://api.example.com/ws');
wsClient.on('user_update', (userData) => {
console.log('User updated:', userData);
});
wsClient.on('notification', (notification) => {
console.log('Notification:', notification);
});
// Connection and message sending
wsClient.connect().then(() => {
wsClient.send('subscribe', { channel: 'user_updates' });
wsClient.send('user_action', { action: 'get_profile', userId: 123 });
});