IT237 Web Technology I

Web Technology IUnit 713 min read

XML & JSON: Data Formats for Web Apps

Unit 7 of Web Technology I explains XML (Extensible Markup Language) and JSON (JavaScript Object Notation) as structured data formats, their syntax, use cases, and how they enable web applications to exchange and store data efficiently. Learn their differences, real-world applications, and implementation in web develop

Key points

  • XML and JSON are **human-readable, machine-parsable** data formats used for storing and exchanging structured data over the web.
  • XML uses **tags** (`<tag>content</tag>`) and supports **attributes**, while JSON uses **key-value pairs** (`{"key": "value"}`) and is lighter for web APIs.
  • JSON is **faster to parse** and widely used in modern web apps (e.g., REST APIs), while XML is **self-descriptive** and used in legacy systems (e.g., SOAP).
  • Both formats enable **data validation**, **interoperability**, and **scalability** in web technologies like AJAX, web services, and configuration files.
  • JSON is **language-independent** but natively supported in JavaScript, making it ideal for frontend-backend communication.
  • Real-world examples include **eSewa’s API responses (JSON)**, **NTC’s service request XML files**, and **Khalti’s transaction logs (JSON)**.
  • ```

1. Introduction to Data Formats in Web Technology

Web applications need a way to store, transmit, and interpret data efficiently. Two dominant formats for this purpose are:

  • XML (Extensible Markup Language): A markup language designed to store and transport data in a structured way.
  • JSON (JavaScript Object Notation): A lightweight data-interchange format, easy for humans to read and write, and easy for machines to parse and generate.

Both are used in APIs, configuration files, and data exchange between client and server. However, they differ in syntax, use cases, and performance.


2. XML: Structure and Syntax

XML is a markup language (like HTML) but designed for data storage and exchange, not presentation. It uses tags to define data elements and supports attributes for additional metadata.

08162431Root Element16 bitsChild Element16 bitsAttribute8 bitsNested Element8 bitsText Content8 bitsClosing Tag8 bits
XML structure breakdown: root, attributes, nested elements, and text content

Key Features of XML

  • Self-descriptive: Tags define the data structure.
  • Supports attributes: Extra information can be stored as attributes (e.g., <book id="101" published="2020">).
  • Case-sensitive: <Name> ≠ <name>.
  • Well-formedness rules: Must have a root element, proper nesting, and closed tags.
  • Schema validation: Can define rules for data structure (DTD, XSD).

Basic XML Syntax

<!-- Example: A simple XML document representing a book -->
<bookstore>
    <book category="fiction">
        <title lang="en">The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>
        <year>1925</year>
        <price>29.99</price>
    </book>
    <book category="non-fiction">
        <title lang="en">Atomic Habits</title>
        <author>James Clear</author>
        <year>2018</year>
        <price>19.99</price>
    </book>
</bookstore>

How XML Works in the Real World

  • NTC (Nepal Telecommunications Corporation) uses XML to structure service request submissions (e.g., new connection requests). The XML file includes user details, service type, and technical specifications.
  • SOAP (Simple Object Access Protocol): A protocol for exchanging structured information in web services, often using XML.
  • Configuration files: Many software systems (e.g., Android’s AndroidManifest.xml) use XML to define app settings.

Advantages of XML

✅ Human-readable and self-descriptive: Easy to understand and debug. ✅ Supports complex data structures: Nested elements, attributes, and namespaces. ✅ Widely supported: Used in legacy systems, databases, and web services. ✅ Schema validation: Ensures data integrity (DTD, XSD).

Disadvantages of XML

❌ Verbose: Requires more characters to represent data (e.g., <price>29.99</price> vs. {"price": 29.99}). ❌ Slower parsing: More complex to process than JSON. ❌ Not native to JavaScript: Requires additional libraries (e.g., DOMParser) to handle.


3. JSON: Structure and Syntax

JSON is a text-based, lightweight data format designed for easy data interchange between a server and a web application. It is language-independent but natively supported in JavaScript.

categorytitleauthoryearpricebookcategorytitleauthoryearpricebookbookstore
JSON object hierarchy: nested key-value pairs representing the bookstore example

Key Features of JSON

  • Key-value pairs: Data is stored as {"key": value}.
  • Supports arrays: Lists of values (e.g., ["apple", "banana", "cherry"]).
  • Data types: Strings, numbers, booleans, arrays, objects, and null.
  • No attributes: Unlike XML, JSON does not support attributes.
  • Minimal syntax: Easier to read and write than XML.

Basic JSON Syntax

{
    "bookstore": [
        {
            "category": "fiction",
            "title": "The Great Gatsby",
            "author": "F. Scott Fitzgerald",
            "year": 1925,
            "price": 29.99
        },
        {
            "category": "non-fiction",
            "title": "Atomic Habits",
            "author": "James Clear",
            "year": 2018,
            "price": 19.99
        }
    ]
}

How JSON Works in the Real World

  • eSewa API: When you check your transaction status, eSewa returns data in JSON format, including transaction_id, amount, status, and timestamp.
  • Khalti’s Payment Gateway: Uses JSON to send and receive payment details between the merchant app and Khalti’s server.
  • REST APIs: Almost all modern web APIs (e.g., YouTube Data API, Twitter API) use JSON for responses.
  • Configuration files: Many modern apps (e.g., package.json in Node.js) use JSON for settings.

Advantages of JSON

✅ Lightweight: Uses fewer characters than XML. ✅ Fast parsing: Easier and faster for computers to process. ✅ Native to JavaScript: No need for additional libraries (unlike XML). ✅ Human-readable: Simple and intuitive syntax.

Disadvantages of JSON

❌ No schema validation: Unlike XML, JSON lacks built-in validation rules (though tools like JSON Schema exist). ❌ Limited data types: No support for dates, binary data, or complex types without workarounds. ❌ No comments: Cannot include comments in JSON files.


4. XML vs. JSON: Comparison

Feature XML JSON
Syntax Uses tags (<tag>content</tag>) Uses key-value pairs ({"key": "value"})
Verbosity More verbose (e.g., <price>29.99</price>) Less verbose ({"price": 29.99})
Attributes Supports attributes (<book id="101">) No attributes (uses nested objects)
Data Types Limited (mostly strings) Supports strings, numbers, booleans, arrays, objects, null
Schema Validation Supports DTD, XSD Relies on external tools (JSON Schema)
Human-Readability High (self-descriptive) High (simple syntax)
Performance Slower to parse Faster to parse
Use Cases Legacy systems, SOAP, config files REST APIs, modern web apps, NoSQL databases
Language Support Requires parsers (e.g., DOM) Native in JavaScript
sequenceDiagram
    participant Client
    participant Server
    Client->>Server: GET /api/books (XML)
    Server-->>Client: <books>
        <book>
            <title>...</title>
            <price>29.99</price>
        </book>
    end
    Client->>Server: GET /api/books (JSON)
    Server-->>Client: {"books": [
        {"title": "...", "price": 29.99}
    ]}
Client-server exchange: XML vs. JSON payload size and structure

5. Real-World Applications

Example 1: eSewa Transaction Status (JSON)

When you check your eSewa transaction status via the app, the server sends a JSON response like this:

{
    "transaction_id": "TXN123456789",
    "status": "completed",
    "amount": 500,
    "timestamp": "2023-10-15T14:30:00Z",
    "recipient": "Nepal Telecom"
}

Why JSON?

  • Lightweight and fast to parse.
  • Easy for the frontend (JavaScript) to handle.
  • No need for complex XML parsing.

Example 2: NTC Service Request (XML)

When you submit a new internet connection request to NTC, they may use an XML file like this:

<service_request>
    <customer>
        <name>John Doe</name>
        <contact>9800000000</contact>
    </customer>
    <service_type>Fiber Internet</service_type>
    <address>Kathmandu, Nepal</address>
    <technical_details>
        <speed>100 Mbps</speed>
        <installation_date>2023-11-01</installation_date>
    </technical_details>
</service_request>

Why XML?

  • Self-descriptive and structured.
  • Supports complex nested data (e.g., technical specifications).
  • Used in legacy systems and SOAP-based services.

Example 3: Daraz Order Queue (JSON)

Daraz’s backend uses JSON to manage order queues. When you place an order, the system might store it as:

{
    "order_id": "ORD789456",
    "user_id": "USER123",
    "items": [
        {"product_id": "P101", "quantity": 2},
        {"product_id": "P102", "quantity": 1}
    ],
    "status": "processing",
    "shipping_address": {
        "street": "Thapathali, Kathmandu",
        "city": "Kathmandu"
    }
}

Why JSON?

  • Easy to update and query in databases (e.g., MongoDB).
  • Fast serialization/deserialization for APIs.

6. When to Use XML or JSON?

Use XML if: Use JSON if:
You need schema validation (DTD/XSD). You need lightweight, fast data.
Working with legacy systems (SOAP, RSS). Building modern web APIs (REST).
Data has complex nested structures. Data is simple and hierarchical.
You need attributes for metadata. You are using JavaScript heavily.
Data is human-edited frequently. Data is machine-generated (e.g., APIs).

7. Parsing XML and JSON in JavaScript

Parsing JSON

JSON is natively supported in JavaScript:

// Example JSON string
const jsonString = '{"name": "John", "age": 30}';

// Parse JSON
const data = JSON.parse(jsonString);
console.log(data.name); // Output: "John"

// Convert object to JSON
const obj = { name: "Jane", age: 25 };
const jsonString2 = JSON.stringify(obj);
console.log(jsonString2); // Output: '{"name":"Jane","age":25}'

Parsing XML

JavaScript does not natively support XML. Use the DOMParser:

const xmlString = `
    <book>
        <title>Atomic Habits</title>
        <author>James Clear</author>
    </book>
`;

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "text/xml");
const title = xmlDoc.getElementsByTagName("title")[0].textContent;
console.log(title); // Output: "Atomic Habits"

8. XML and JSON in Web APIs

REST API Example (JSON)

When you fetch data from an API (e.g., YouTube API), the response is usually JSON:

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: GET /api/videos?query=web%20tech
    Server-->>Client: HTTP 200 OK\nContent-Type: application/json
    Client->>Client: Parse JSON response

Example Response:

{
    "videos": [
        {
            "id": "VID1",
            "title": "Introduction to Web Tech",
            "duration": "10:30"
        },
        {
            "id": "VID2",
            "title": "XML vs JSON",
            "duration": "8:15"
        }
    ]
}

SOAP API Example (XML)

SOAP APIs (e.g., some banking services) use XML:

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: SOAP Request (XML)
    Server-->>Client: SOAP Response (XML)

Example Request:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <getBalance>
            <accountNumber>123456789</accountNumber>
        </getBalance>
    </soapenv:Body>
</soapenv:Envelope>

9. Exam Tip

  1. Understand the syntax: Be able to write simple XML and JSON examples from scratch.
  2. Know the differences: XML is verbose and supports attributes; JSON is lightweight and uses key-value pairs.
  3. Real-world applications:
    • JSON is used in REST APIs, modern web apps (eSewa, Khalti, Daraz).
    • XML is used in legacy systems, SOAP, configuration files (NTC, Ncell).
  4. Parsing in JavaScript:
    • JSON: JSON.parse() and JSON.stringify().
    • XML: DOMParser for parsing.
  5. Common exam questions:
    • Compare XML and JSON (use the comparison table).
    • Explain how JSON is used in a real-world API (e.g., eSewa transaction).
    • Write a simple XML/JSON example for a given scenario (e.g., a bookstore).

In the real world

  • eSewa API (JSON): When you check a transaction status, eSewa’s backend sends a JSON response with fields like transaction_id, status, and amount. This lightweight format ensures fast parsing in the mobile app’s JavaScript frontend.
  • NTC Service Requests (XML): Nepal Telecommunications Corporation uses XML to structure technical service requests (e.g., fiber internet connections) because it supports nested attributes like <service_type>Fiber Internet</service_type> and <technical_specs>...</technical_specs>.
  • Khalti Payment Gateway (JSON): During a transaction, Khalti’s server sends/receives payment details in JSON (e.g., {"amount": 500, "currency": "NPR", "status": "pending"}) for real-time processing in merchant apps.

Based on the TU BITM syllabus for Web Technology I (IT237), unit 7.

Discussion

Loading…