Web Technology IUnit 712 min read
XML vs JSON: Data Formats, Syntax, and Real-World Use Cases
Unit 7 of Web Technology I covers XML (eXtensible Markup Language) and JSON (JavaScript Object Notation), their syntax, structure, and applications in web development, including data exchange, configuration files, and APIs. Learn how to read, write, and compare these formats with practical examples from Nepali and glob
What Are XML and JSON?
XML and JSON are data formats used to structure, store, and exchange data between systems. They are human-readable and machine-parsable, meaning both developers and computers can understand them.
Key Definitions:
XML (eXtensible Markup Language):
- A markup language (like HTML) but designed for data storage and transport.
- Uses tags (
<tag>content</tag>) to define data structure. - Supports attributes, namespaces, and complex hierarchies.
- Example: Config files, SOAP web services, RSS feeds.
JSON (JavaScript Object Notation):
- A lightweight data-interchange format (not a markup language).
- Uses key-value pairs (
{ "key": "value" }) and arrays ([1, 2, 3]). - Simpler syntax, widely used in APIs (e.g., REST) and NoSQL databases.
XML: Structure and Syntax
XML organizes data in a tree-like hierarchy using tags, attributes, and nested elements.
Core Components:
- Elements: Defined by opening (
<tag>) and closing (</tag>) tags.<book> <title>Web Tech 101</title> <author>John Doe</author> </book> - Attributes: Provide additional metadata inside opening tags.
<book id="101" published="2023"> <title lang="en">Web Tech 101</title> </book> - Comments: Ignored by parsers (
<!-- This is a comment -->). - Namespaces: Avoid tag conflicts (e.g.,
xmlns:ns="http://example.com").
Example: Student Record in XML
<student>
<id>STU001</id>
<name>
<first>Ramesh</first>
<last>Adhikari</last>
</name>
<courses>
<course>Web Technology</course>
<course>Database Systems</course>
</courses>
</student>
JSON: Structure and Syntax
JSON represents data as key-value pairs or ordered lists (arrays). It is lighter and faster to parse than XML.
Core Components:
- Objects: Key-value pairs enclosed in
{}.{ "name": "Ramesh Adhikari", "id": "STU001", "courses": ["Web Technology", "Database Systems"] } - Arrays: Ordered lists enclosed in
[].{ "students": [ {"id": "STU001", "name": "Ramesh"}, {"id": "STU002", "name": "Sita"} ] } - Data Types: Supports strings (
"text"), numbers (42), booleans (true),null, objects, and arrays.
Example: Same Student Record in JSON
{
"student": {
"id": "STU001",
"name": {
"first": "Ramesh",
"last": "Adhikari"
},
"courses": ["Web Technology", "Database Systems"]
}
}
XML vs. JSON: Comparison Table
| Feature | XML | JSON |
|---|---|---|
| Syntax | Tags (<tag>content</tag>) |
Key-value pairs ({}) |
| Readability | Verbose, complex | Compact, simple |
| Use Case | Config files, SOAP, RSS | APIs (REST), NoSQL databases |
| Size | Larger | Smaller |
| Parsing Speed | Slower | Faster |
| Data Types | Limited (text, numbers) | Rich (strings, numbers, bools, arrays, objects) |
| Attributes | Supported | Not supported (use objects) |
| Human Editing | Harder (tags, nesting) | Easier (plain text) |
In the Real World
- eSewa (Nepal):
- Uses JSON for API responses when fetching user transaction history or payment status.
- Example: When you check your eSewa balance via the app, the server sends a JSON response like:
{ "user": { "balance": 5000, "last_transaction": { "amount": 200, "type": "electricity" } } }
sequenceDiagram
participant User
participant DarazAPI as Daraz API (JSON)
participant Warehouse as Warehouse System (XML)
participant Courier as Courier API (JSON)
User->>DarazAPI: POST /orders (JSON payload)
DarazAPI-->>User: {"status":"success", "order_id":"ORD5678"} (JSON)
DarazAPI->>Warehouse: <inventory>...</inventory> (XML)
Warehouse-->>DarazAPI: Updated stock (XML)
DarazAPI->>Courier: {"order":{"id":"ORD5678"}} (JSON)
Courier-->>DarazAPI: Delivery confirmation (JSON)Daraz order processing: JSON for APIs, XML for legacy warehouse systemsKhalti (Nepal):
- Relies on XML for secure payment gateways (especially in older systems) and JSON for modern APIs.
- Example: When you request a payment link, Khalti’s backend might return:
{ "payment_link": "https://khalti.com/pay?order_id=12345", "qr_code": "base64_encoded_qr_string" }
YouTube (Global):
- Uses JSON to serve video metadata (title, duration, views) when you search for a video.
- Example API response snippet:
{ "video": { "title": "Web Tech Tutorial", "duration": "12:34", "views": 1000000, "thumbnail": "https://i.ytimg.com/..." } }
NTC (Nepal Telecom):
- Uses XML in legacy systems for billing data exchange between NTC’s central server and local offices.
- Example: A customer’s bill might be structured as:
<bill> <customer_id>CUST123</customer_id> <phone_number>9800012345</phone_number> <total_amount>1200</total_amount> <due_date>2023-12-31</due_date> </bill>
Worked Example: Daraz Order Processing
Imagine Daraz’s backend processes an order from Pokhara to Kathmandu. The order data is sent as JSON to the warehouse system.
Step-by-Step Trace:
User Places Order:
- Frontend (React.js) sends a POST request to Daraz’s API with order details in JSON:
{ "order_id": "ORD5678", "user": "user123", "items": [ { "product_id": "PROD999", "quantity": 2, "price": 500 } ], "shipping_address": { "city": "Kathmandu", "pincode": "44600" } }
- Frontend (React.js) sends a POST request to Daraz’s API with order details in JSON:
Backend Validation:
- Daraz’s server (Node.js) validates the JSON, checks stock, and updates the database.
- Response to user:
{ "status": "success", "order_id": "ORD5678", "estimated_delivery": "2023-11-15" }
Warehouse System:
- The warehouse uses XML for internal inventory updates (legacy system):
<inventory> <product id="PROD999"> <quantity>18</quantity> <!-- Updated from 20 to 18 --> </product> </inventory>
- The warehouse uses XML for internal inventory updates (legacy system):
Courier Integration:
- Daraz’s courier API (e.g., Ncell’s Pathao) receives the order as JSON:
{ "order": { "id": "ORD5678", "pickup": "Daraz Warehouse, Lalitpur", "delivery": "Kathmandu-44600", "items": [ { "name": "Smartphone", "weight": 0.5 } ] } }
- Daraz’s courier API (e.g., Ncell’s Pathao) receives the order as JSON:
When to Use XML vs. JSON
Use XML when:
- You need complex data structures (e.g., scientific data, legal documents).
- Legacy systems require XML (e.g., SOAP web services).
- Human readability is critical for large documents (e.g., config files).
- Attributes are useful (e.g.,
<tag attr="value">).
Use JSON when:
- Working with web APIs (REST, GraphQL).
- Performance is critical (smaller payload, faster parsing).
- Data is simple and hierarchical (e.g., user profiles, product catalogs).
- JavaScript is involved (native JSON support in JS).
Parsing XML and JSON
XML Parsing:
- DOM Parser: Loads the entire XML into memory (good for small files).
- SAX Parser: Event-based, reads XML sequentially (better for large files).
- XPath/XQuery: Query XML data (e.g.,
//book[@id="101"]).
JSON Parsing:
- Built-in in JavaScript:
JSON.parse()andJSON.stringify(). - Libraries:
jQuery.parseJSON(), Python’sjsonmodule, Java’sorg.json.
Common Pitfalls and Best Practices
XML Pitfalls:
- Verbose: Can bloat file sizes.
- Complexity: Nested tags can be hard to debug.
- Case Sensitivity: Tags are case-sensitive (
<Name>≠<name>).
JSON Pitfalls:
- No Comments: Unlike XML, JSON has no native comment syntax.
- Limited Data Types: No support for dates without strings (e.g.,
"2023-11-15"). - Trailing Commas: Invalid in strict JSON (e.g.,
{ "key": "value", }is invalid).
Best Practices:
- Validate Data: Use XML Schema (XSD) or JSON Schema to enforce structure.
- Minify JSON: Remove whitespace for smaller payloads.
- Use Meaningful Keys: Avoid vague keys like
data1,data2; useuser_id,order_date. - Secure APIs: Sanitize JSON inputs to prevent injection attacks.
Exam Tip
Syntax Matters:
- Memorize the basic structure of XML (tags, attributes) and JSON (objects, arrays).
- Know how to write valid XML/JSON (e.g., closing tags, proper nesting, no trailing commas in JSON).
Real-World Applications:
- Expect comparison questions (XML vs. JSON). Highlight differences in use cases, size, and parsing speed.
- Be ready to write examples (e.g., student record, order data) in both formats.
Parsing and Validation:
- Understand how DOM/SAX parsers work for XML and how
JSON.parse()works in JavaScript. - Know what JSON Schema and XML Schema (XSD) are used for.
- Understand how DOM/SAX parsers work for XML and how
Common Exam Questions:
- "Convert the following XML to JSON" or vice versa.
- "When would you use XML over JSON in a web application?"
- "Explain how Daraz might use JSON to process an order (trace the flow)."
Diagrams:
- Draw a tree structure for XML and a key-value hierarchy for JSON to visually compare them.
- Use a sequence diagram to show how a JSON API request flows between client and server (e.g., eSewa balance check).
classDiagram
class XML {
-Uses tags and attributes
-Hierarchical structure
-Verbose syntax
+Methods: DOM/SAX parsing
}
class JSON {
-Uses key-value pairs
-Flat or nested objects/arrays
-Compact syntax
+Methods: JSON.parse(), JSON.stringify()
}
XML --> "Converts to" JSON : XSLT/Manual
JSON --> "Converts to" XML : Manual/XMLGenerator
XML : +Used in: SOAP, RSS, config files
JSON : +Used in: REST APIs, NoSQL, web appsBased on the TU BIM syllabus for Web Technology I (IT237), unit 7.
Discussion
Loading…