JSON5 to JSON
What is JSON5?
JSON5 is an extension of JSON (JavaScript Object Notation) that aims to make it easier for humans to write and maintain by hand. JSON5 remains backward compatible with JSON while adding several syntactic improvements inspired by ECMAScript 5.1.
Key Differences Between JSON5 and JSON
Comparison Table
Feature | JSON | JSON5 | Example |
---|---|---|---|
Comments | ❌ Not allowed | ✅ Single-line // and multi-line /* */ | // This is a comment |
Trailing Commas | ❌ Not allowed | ✅ Allowed in objects and arrays | {"a": 1,} |
Unquoted Keys | ❌ Must be quoted | ✅ Allowed for valid identifiers | {name: "John"} |
Single Quotes | ❌ Must use double quotes | ✅ Allowed for strings | {'name': 'John'} |
Multi-line Strings | ❌ Not supported | ✅ Backslash-escaped newlines | "line1\\\nline2" |
Number Formats | ❌ Limited formats | ✅ Hexadecimal, leading/trailing decimal | 0xFF , .5 , 2. |
Infinity/NaN | ❌ Not supported | ✅ Supported | Infinity , -Infinity , NaN |
JSON5 Features in Detail
1. Comments
JSON5 supports both single-line and multi-line comments:
{
// Single-line comment
"name": "John Doe",
/* Multi-line comment
can span multiple lines */
"age": 30
}
2. Trailing Commas
Trailing commas are allowed in objects and arrays:
{
"fruits": [
"apple",
"banana",
"orange", // <- trailing comma allowed
],
"count": 3, // <- trailing comma allowed
}
3. Unquoted Object Keys
Object keys can be unquoted if they are valid ECMAScript identifiers:
{
name: "John Doe", // unquoted key
firstName: "John", // unquoted key
"last-name": "Doe", // must be quoted (contains hyphen)
"2ndName": "Smith" // must be quoted (starts with number)
}
4. Single Quotes for Strings
Strings can use single quotes instead of double quotes:
{
'name': 'John Doe',
'message': "Hello 'world'", // mixing quotes
"response": 'He said "Hi"' // mixing quotes
}
5. Multi-line Strings
Strings can span multiple lines using backslash-escaped newlines:
{
"poem": "Roses are red,\
Violets are blue,\
JSON5 is great,\
And so are you!"
}
6. Extended Number Formats
Hexadecimal Numbers
{
"color": 0xFF0000, // red in hex
"mask": 0x00FF00 // green in hex
}
Leading and Trailing Decimal Points
{
"probability": .5, // same as 0.5
"ratio": 2., // same as 2.0
"precise": .25 // same as 0.25
}
Infinity and NaN
{
"maximum": Infinity,
"minimum": -Infinity,
"undefined": NaN
}
Why Convert JSON5 to JSON?
1. API Compatibility
Most web APIs and services expect standard JSON format:
// JSON5 config file
{
apiUrl: "https://api.example.com",
timeout: 5000, // 5 seconds
retries: 3, // max retries
}
// Must convert to JSON for API transmission
{
"apiUrl": "https://api.example.com",
"timeout": 5000,
"retries": 3
}
2. Legacy System Support
Older systems and parsers may not support JSON5:
// JSON5 user preferences
{
theme: 'dark',
fontSize: 14,
features: {
spellCheck: true,
autoSave: true, // trailing comma
}
}
// Convert to JSON for older browsers
{
"theme": "dark",
"fontSize": 14,
"features": {
"spellCheck": true,
"autoSave": true
}
}
3. Data Storage
Databases and storage systems typically require standard JSON:
// JSON5 document
{
_id: "user_123",
name: "Alice Johnson",
// User preferences
settings: {
notifications: true,
privacy: 'public', // single quotes
},
}
// Convert for database storage
{
"_id": "user_123",
"name": "Alice Johnson",
"settings": {
"notifications": true,
"privacy": "public"
}
}
Conversion Process
Transformations Applied
- Remove Comments
// JSON5 { // User data name: "John" } // JSON { "name": "John" }
- Quote Object Keys
// JSON5 { firstName: "John", lastName: "Doe" } // JSON { "firstName": "John", "lastName": "Doe" }
- Convert Single Quotes to Double Quotes
// JSON5 { 'message': 'Hello world' } // JSON { "message": "Hello world" }
- Remove Trailing Commas
// JSON5 { "items": [1, 2, 3,], "count": 3, } // JSON { "items": [1, 2, 3], "count": 3 }
- Convert Number Formats
// JSON5 { hex: 0xFF, decimal: .5, infinity: Infinity } // JSON { "hex": 255, "decimal": 0.5, "infinity": null }
- Handle Multi-line Strings
// JSON5 { text: "Line 1\ Line 2" } // JSON { "text": "Line 1Line 2" }
Conversion Examples
Example 1: Configuration File
JSON5 Input:
{
// Application configuration
app: {
name: 'MyApplication',
version: '1.2.3',
debug: true,
},
// Database settings
database: {
host: 'localhost',
port: 5432,
ssl: false,
timeout: 30000, // 30 seconds
},
// Feature flags
features: {
authentication: true,
analytics: false,
'beta-features': true, // quoted key (contains hyphen)
},
}
JSON Output:
{
"app": {
"name": "MyApplication",
"version": "1.2.3",
"debug": true
},
"database": {
"host": "localhost",
"port": 5432,
"ssl": false,
"timeout": 30000
},
"features": {
"authentication": true,
"analytics": false,
"beta-features": true
}
}
Example 2: API Response Template
JSON5 Input:
{
status: 'success',
code: 200,
message: 'Data retrieved successfully',
data: {
users: [
{
id: 1,
name: 'Alice Johnson',
email: '[email protected]',
active: true,
},
{
id: 2,
name: 'Bob Smith',
email: '[email protected]',
active: false, // trailing comma
},
],
/* Pagination info */
pagination: {
page: 1,
limit: 10,
total: 2,
hasNext: false,
},
},
timestamp: '2024-01-15T10:30:00Z',
}
JSON Output:
{
"status": "success",
"code": 200,
"message": "Data retrieved successfully",
"data": {
"users": [
{
"id": 1,
"name": "Alice Johnson",
"email": "[email protected]",
"active": true
},
{
"id": 2,
"name": "Bob Smith",
"email": "[email protected]",
"active": false
}
],
"pagination": {
"page": 1,
"limit": 10,
"total": 2,
"hasNext": false
}
},
"timestamp": "2024-01-15T10:30:00Z"
}
Example 3: Complex Data Structure
JSON5 Input:
{
// Product catalog
products: [
{
id: 'prod_001',
name: 'Gaming Laptop',
price: 1299.99,
specs: {
cpu: 'Intel i7',
ram: '16GB',
storage: '512GB SSD',
graphics: 'NVIDIA RTX 3060',
},
colors: ['black', 'silver',], // trailing comma
inStock: true,
},
],
// Metadata
meta: {
version: '2.1',
lastUpdated: '2024-01-15',
/* Currency settings */
currency: {
code: 'USD',
symbol: '$',
precision: 2,
},
},
}
JSON Output:
{
"products": [
{
"id": "prod_001",
"name": "Gaming Laptop",
"price": 1299.99,
"specs": {
"cpu": "Intel i7",
"ram": "16GB",
"storage": "512GB SSD",
"graphics": "NVIDIA RTX 3060"
},
"colors": ["black", "silver"],
"inStock": true
}
],
"meta": {
"version": "2.1",
"lastUpdated": "2024-01-15",
"currency": {
"code": "USD",
"symbol": "$",
"precision": 2
}
}
}
Conversion Considerations
1. Loss of Comments
Comments are removed during conversion:
// JSON5 - rich with documentation
{
// API endpoint for user authentication
authUrl: '/api/auth',
// Maximum retry attempts
maxRetries: 3
}
// JSON - comments lost
{
"authUrl": "/api/auth",
"maxRetries": 3
}
2. Special Number Values
Infinity and NaN require special handling:
// JSON5
{
maximum: Infinity,
minimum: -Infinity,
invalid: NaN
}
// JSON - converted to null or string
{
"maximum": null, // or "Infinity"
"minimum": null, // or "-Infinity"
"invalid": null // or "NaN"
}
3. Multi-line String Formatting
Multi-line strings are flattened:
// JSON5 - readable multi-line
{
description: "This is a very long description\
that spans multiple lines for better\
readability in the source code"
}
// JSON - single line
{
"description": "This is a very long descriptionthat spans multiple lines for betterreadability in the source code"
}
Best Practices
1. Use JSON5 for Configuration
// config.json5 - human-friendly
{
// Server configuration
server: {
port: 3000,
host: 'localhost',
},
// Database settings
database: {
url: 'mongodb://localhost:27017',
options: {
useNewUrlParser: true,
useUnifiedTopology: true,
},
},
}
2. Convert to JSON for APIs
// Build process: JSON5 → JSON
const json5Content = fs.readFileSync('config.json5', 'utf8');
const jsonContent = JSON5.stringify(JSON5.parse(json5Content));
fs.writeFileSync('config.json', jsonContent);
3. Document Conversion Rules
When converting JSON5 to JSON, document what transformations are applied:
- Comments removed
- Keys quoted
- Trailing commas removed
- Single quotes converted to double quotes
- Special numbers (Infinity, NaN) converted to null
- Multi-line strings flattened
Tools and Libraries
JavaScript
// Using json5 library
const JSON5 = require('json5');
// Parse JSON5
const obj = JSON5.parse(json5String);
// Convert to JSON
const jsonString = JSON.stringify(obj);
Command Line
# Using json5 CLI
npm install -g json5
json5 -c config.json5 > config.json
Online Converters
- JSON5 to JSON online tools
- IDE plugins for automatic conversion
- Build system integrations
Use Cases
1. Configuration Files
- Application settings
- Build configurations
- Environment variables
2. Documentation
- API specifications
- Data schemas
- Example responses
3. Development
- Mock data with comments
- Test fixtures
- Development configurations
Conclusion
JSON5 provides a more human-friendly way to write JSON with features like:
- Comments for documentation
- Trailing commas for easier editing
- Unquoted keys for cleaner syntax
- Flexible string quoting
- Extended number formats
Converting JSON5 to JSON is essential for:
- API compatibility
- Legacy system support
- Standard compliance
- Tool interoperability
While some information (like comments) is lost in conversion, the resulting JSON maintains all the essential data while ensuring compatibility with systems that require standard JSON format.