JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JSON Object Literals

15 April 2025 | Category:

A JSON Object Literal is a structured data format that represents data using key-value pairs, similar to JavaScript objects — but with stricter rules.

✅ JSON is a text-based format for storing and exchanging data, while object literals are JavaScript code.


📘 Example: JSON Object Literal

{
  "name": "Alice",
  "age": 25,
  "isStudent": false,
  "skills": ["HTML", "CSS", "JavaScript"],
  "address": {
    "city": "Delhi",
    "zip": "110001"
  }
}

JSON object literal is usually written inside curly braces {} with key-value pairs separated by commas.


🧠 JSON Object Literal vs JavaScript Object

FeatureJSONJavaScript Object
Quotes for keysRequired (double quotes)Optional
Quotes for stringsMust use double quotesCan use single or double quotes
Function support❌ Not allowed✅ Allowed
Data types supportedstring, number, boolean, null, array, objectAll JS types

Example:

// JSON - Strict format
const jsonData = '{ "name": "Alice", "age": 25 }';

// JS Object - More flexible
const jsObj = { name: "Alice", age: 25 };

✅ Using JSON Object Literals in Code

You can convert a JSON string to a JavaScript object using JSON.parse():

const jsonString = '{ "name": "Alice", "age": 25 }';

const userObj = JSON.parse(jsonString);

console.log(userObj.name); // Output: Alice

You can also convert a JavaScript object to a JSON string using JSON.stringify():

const user = { name: "Bob", age: 30 };

const jsonStr = JSON.stringify(user);

console.log(jsonStr);
// Output: {"name":"Bob","age":30}

✅ Data Types Allowed in JSON Object Literals

  1. String
    "name": "John"
  2. Number
    "age": 30
  3. Boolean
    "isActive": true
  4. Null
    "spouse": null
  5. Array
    "skills": ["HTML", "CSS"]
  6. Object
    "address": { "city": "Delhi" }

⚠️ JSON Object Literal Rules

  • Keys must be in double quotes.
  • Strings must use double quotes.
  • No functions or comments allowed.
  • Values must be one of the allowed data types.

🔚 Summary

  • JSON Object Literals represent structured data in key-value format.
  • They are used widely in APIs, configurations, and data exchange.
  • They follow strict syntax compared to JavaScript objects.