JSON, XML, and HTTP Methods
In-Depth Guide for IT and Network Engineers
1. JSON (JavaScript Object Notation)
What is JSON?
JSON is a lightweight, text-based data-interchange format that represents structured data as key-value pairs and arrays. It is commonly used for data exchange between web clients and servers, especially in RESTful APIs and web applications.
JSON Syntax and Structure
- Objects: Key-value pairs, wrapped in
{ } - Arrays: Ordered lists, wrapped in
[ ] - Key-Value Pairs:
"key": value - Data Types: String, number, boolean, null, object, array
Example:
{
"name": "John",
"age": 30,
"skills": ["Networking", "Programming"],
"isActive": true,
"address": null
}
Use Cases of JSON
- Data exchange in RESTful APIs (
Content-Type: application/json) - Configuration files (
package.jsonin Node.js) - Data storage in NoSQL databases (like MongoDB)
Parsing and Generating JSON
In Python:
import json
data = json.loads('{"name": "John"}') # Parse JSON string
json_str = json.dumps(data) # Convert Python object to JSON string
In JavaScript:
let obj = JSON.parse('{"name":"John"}'); // Parse JSON
let str = JSON.stringify(obj); // Convert to JSON string
Advantages of JSON over XML
- More readable and compact
- Easier to parse in most programming languages
- Native support in JavaScript (important for web apps)
2. XML (eXtensible Markup Language)
What is XML?
XML is a markup language designed to store and transport data using custom tags. It enables platform-independent, hierarchical data representation.
XML Syntax and Structure
- Elements:
<tag>value</tag> - Attributes:
<tag attr="value">content</tag> - Hierarchy: Elements can be nested to represent complex data
Example:
<person>
<name>John</name>
<age>30</age>
<skills>
<skill>Networking</skill>
<skill>Programming</skill>
</skills>
</person>
Use Cases of XML
- Legacy data storage and transfer
- Enterprise configuration files (e.g.,
web.configin ASP.NET) - Web services (SOAP APIs)
Parsing and Validating XML
- Python:
xml.etree.ElementTreeorlxmllibraries - Java:
DocumentBuilderFactory - Validation: XML Schema Definition (XSD) for structure/content validation
Advantages and Disadvantages of XML
| Advantages | Disadvantages |
|---|---|
|
|
3. HTTP Methods (GET, POST, PUT, DELETE)
Overview of HTTP Protocol
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web, operating on a client-server model. A client sends a request, and the server responds.
- Request: Method (GET, POST, etc.), URL, headers, body (optional)
- Response: Status code, headers, body
GET Method
- Purpose: Retrieve (read) data from a server
- Idempotent and safe: Multiple identical requests have the same effect, no change to server state
- Data sent as URL parameters (query string)
- Caching: Often cached by browsers/proxies
GET /api/users/1 HTTP/1.1 Host: example.com
POST Method
- Purpose: Submit data to the server, typically to create a new resource
- Non-idempotent: Multiple requests may create multiple resources
- Data sent in the request body (not in URL)
- Not cached by default
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "John",
"role": "Admin"
}
PUT Method
- Purpose: Update an existing resource or create it at a specified URI
- Idempotent: Repeated identical requests have the same effect
- Data sent in the body; typically the complete new resource
PUT /api/users/1 HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "John",
"role": "Super Admin"
}
DELETE Method
- Purpose: Remove a specified resource
- Idempotent: Deleting the same resource multiple times results in the same outcome
- Usually no request body
DELETE /api/users/1 HTTP/1.1 Host: example.com
Differences Between HTTP Methods
| Method | Purpose | Idempotent | Request Body | Changes Server State | Use Case Example |
|---|---|---|---|---|---|
| GET | Retrieve data | Yes | No | No | Fetch user list |
| POST | Create resource | No | Yes | Yes | Create new user |
| PUT | Update/create | Yes | Yes | Yes | Update user info |
| DELETE | Delete resource | Yes | Usually No | Yes | Remove a user |
HTTP Status Codes Related to Methods
- Success: 200 OK, 201 Created, 204 No Content
- Client errors: 400 Bad Request, 401 Unauthorized, 404 Not Found
- Server errors: 500 Internal Server Error
Security Considerations
- Safe methods: GET, HEAD (should not modify data)
- Unsafe methods: POST, PUT, DELETE (can modify server state)
- Data exposure: GET parameters visible in URLs and logs; POST data is in the body (less exposed)
- Best practice: Never send sensitive data in URLs. Always use HTTPS for secure transmission.
Hands-On Practice and Example Code
1. Parsing and Generating JSON
Python Example- Parsing a JSON String
import json
json_string = '{"name": "John", "age": 28, "skills": ["Networking", "Python"]}'
data = json.loads(json_string)
print(data['name']) # Output: John
- Generating (Serializing) a Python Object to JSON
person = {
"name": "John",
"age": 28,
"skills": ["Networking", "Python"]
}
json_output = json.dumps(person)
print(json_output)
JavaScript Example
- Parsing JSON
let jsonString = '{"name": "John", "age": 28, "skills": ["Networking", "JavaScript"]}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // Output: John
- Generating JSON
let person = {
name: "John",
age: 28,
skills: ["Networking", "JavaScript"]
};
let jsonStr = JSON.stringify(person);
console.log(jsonStr);
2. Parsing and Generating XML
Python Example (Usingxml.etree.ElementTree)
- Parsing XML
import xml.etree.ElementTree as ET
xml_string = """
<person>
<name>John</name>
<age>28</age>
<skills>
<skill>Networking</skill>
<skill>Python</skill>
</skills>
</person>
"""
root = ET.fromstring(xml_string)
print(root.find('name').text) # Output: John
- Generating XML
import xml.etree.ElementTree as ET
person = ET.Element('person')
name = ET.SubElement(person, 'name')
name.text = 'John'
age = ET.SubElement(person, 'age')
age.text = '28'
skills = ET.SubElement(person, 'skills')
skill1 = ET.SubElement(skills, 'skill')
skill1.text = 'Networking'
skill2 = ET.SubElement(skills, 'skill')
skill2.text = 'Python'
xml_output = ET.tostring(person, encoding='unicode')
print(xml_output)
JavaScript XML Parsing (with browser DOMParser)
- Parsing XML in Browser
let xmlString = `
<person>
<name>John</name>
<age>28</age>
<skills>
<skill>Networking</skill>
<skill>JavaScript</skill>
</skills>
</person>
`;
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(xmlString, "text/xml");
console.log(xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue); // Output: John
3. Making HTTP Requests
Python Example (requests Library)- GET Request
import requests
response = requests.get('https://jsonplaceholder.typicode.com/users/1')
print(response.json()) # Data for a user (simulated)
- POST Request
import requests
payload = {
"name": "John",
"username": "john123"
}
response = requests.post('https://jsonplaceholder.typicode.com/users', json=payload)
print(response.json())
- PUT Request
import requests
payload = {
"name": "John",
"username": "john_updated"
}
response = requests.put('https://jsonplaceholder.typicode.com/users/1', json=payload)
print(response.json())
- DELETE Request
import requests
response = requests.delete('https://jsonplaceholder.typicode.com/users/1')
print(response.status_code) # 200 (success) or 204 (no content)
JavaScript Example (Fetch API)
- GET Request
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => console.log(data));
- POST Request
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: "John",
username: "john123"
})
})
.then(response => response.json())
.then(data => console.log(data));
- PUT Request
fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: "John",
username: "john_updated"
})
})
.then(response => response.json())
.then(data => console.log(data));
- DELETE Request
fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'DELETE'
})
.then(response => console.log(response.status));
Practice Tasks
- Modify the code above to add more fields (e.g., email, city) and print them.
- Experiment with sending HTTP requests to jsonplaceholder.typicode.com and observe the status codes and response bodies.
- Try different HTTP methods and see their effects (POST vs. PUT vs. DELETE).
- Convert user information ("John") between JSON and XML formats to see the structural differences.
Key Points for the Exam
- Know the syntax and structure of JSON and XML, and their parsing in code.
- Understand HTTP method purpose, idempotency, and when to use each.
- Be able to explain common HTTP status codes and security best practices.
- Test knowledge using tools like Postman, curl, Python
requests, or JavaScriptfetch.