Xml & Json
🧩 1. What is JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format.
It is easy for humans to read and write, and easy for machines to parse and generate.
Used in:
API responses and requests
Config files
Data transfer between front-end and back-end
⚙️ 2. JSON Syntax Rules
| Concept | Description | Example |
| Object | Collection of key-value pairs inside {} | { "name": "John", "age": 30 } |
| Array | Ordered list of values inside [] | [ "apple", "banana", "cherry" ] |
| Key | Always a string, wrapped in quotes | "name" |
| Value | Can be string, number, object, array, boolean, or null | "John", 30, true, null |
| Comma | Separates key-value pairs | { "a":1, "b":2 } |
📘 3. Example JSON Structure
{
"id": 101,
"name": "Shreenibas",
"email": "shree@example.com",
"isActive": true,
"skills": ["Java", "Selenium", "API Testing"],
"address": {
"city": "Bhubaneswar",
"pincode": 751024
}
}
🧠 4. JSON Data Types
| Type | Example |
| String | "Hello" |
| Number | 25, 3.14 |
| Boolean | true / false |
| Null | null |
| Object | { "key": "value" } |
| Array | [1,2,3] or [{"id":1},{"id":2}] |
🧰 5. JSON in Java (Parsing and Serialization)
🔹 Using org.json
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String jsonData = "{ \"name\": \"Shree\", \"age\": 30 }";
JSONObject obj = new JSONObject(jsonData);
System.out.println(obj.getString("name")); // Shree
System.out.println(obj.getInt("age")); // 30
}
}
🔹 Using Jackson (faster and widely used)
➤ Convert JSON → Java Object (Deserialization)
import com.fasterxml.jackson.databind.ObjectMapper;
public class Demo {
public static void main(String[] args) throws Exception {
String json = "{ \"name\":\"Shree\", \"age\":30 }";
ObjectMapper mapper = new ObjectMapper();
Person p = mapper.readValue(json, Person.class);
System.out.println(p.getName());
}
}
class Person {
private String name;
private int age;
// getters and setters
}
➤ Convert Java Object → JSON (Serialization)
Person p = new Person();
p.setName("Shree");
p.setAge(30);
ObjectMapper mapper = new ObjectMapper();
String jsonOutput = mapper.writeValueAsString(p);
System.out.println(jsonOutput);
Output:
{"name":"Shree","age":30}
🧪 6. JSON in Rest Assured
✅ Extract value from API response
Response res = given().get("https://api.example.com/users/1");
String name = res.jsonPath().getString("name");
int id = res.jsonPath().getInt("id");
✅ Send JSON payload in POST request
JSONObject request = new JSONObject();
request.put("name", "Shree");
request.put("job", "Tester");
given()
.header("Content-Type", "application/json")
.body(request.toString())
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
🔍 7. JSON Path (for reading JSON)
| Expression | Description | Example Output |
store.book[0].title | Get title of first book | “Java Basics” |
store.book[-1].price | Get last book’s price | 30.5 |
store.book.find { it.price > 10 } | Find book where price > 10 | Object |
store.book.size() | Count books | 3 |
🚀 8. JSON Schema Validation in Rest Assured
Used to validate API responses against predefined structure.
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
given()
.get("/users/1")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("userSchema.json"));
🧩 9. Common JSON Errors
| Error | Reason | Fix |
| Missing quotes | Keys must be in quotes | "name": "John" |
| Trailing comma | Last pair shouldn’t end with comma | Remove comma |
| Invalid nesting | Braces/Brackets mismatch | Check {} and [] balance |
💡 10. Practice Tasks
Create JSON for Employee → name, id, skills[], address{}
Parse JSON and extract nested values
Convert List of POJOs to JSON array using Jackson
Validate JSON response schema in RestAssured
Write test that compares expected and actual JSONs
Would you like me to create a practice-based JSON mini project (like validating API responses or reading test data from JSON in Selenium)?
It can be beginner → advanced in 3 levels.
You said:
json path
ChatGPT said:
Perfect 👍 — let’s now go deep into JSONPath, which is one of the most powerful and frequently asked topics for API automation (RestAssured) and JSON parsing.
🧩 JSONPath Tutorial (Complete Guide for Testers)
💡 What is JSONPath?
JSONPath is a query language for navigating and extracting data from JSON documents, just like XPath for XML.
It helps you get specific values, arrays, or nested data easily.
Example JSON:
{
"store": {
"book": [
{ "category": "fiction", "title": "The Alchemist", "price": 12.99 },
{ "category": "programming", "title": "Java Basics", "price": 25.50 },
{ "category": "fiction", "title": "Harry Potter", "price": 30.00 }
],
"bicycle": {
"color": "red",
"price": 120.50
}
}
}
⚙️ Basic JSONPath Syntax
| Symbol | Meaning | Example | Output |
$ | Root element | $ | whole JSON |
. | Child operator | $.store.book | all books |
[] | Array index | $.store.book[0] | 1st book |
* | Wildcard (all elements) | $.store.book[*].title | all book titles |
.. | Recursive search | $..price | all prices |
@ | Current element | $.store.book[?(@.price > 20)] | books with price > 20 |
🧠 Examples
| Expression | Description | Output |
$.store.book[0].title | Title of 1st book | "The Alchemist" |
$.store.book[*].price | All book prices | [12.99, 25.50, 30.00] |
$..price | All prices (book + bicycle) | [12.99, 25.50, 30.00, 120.50] |
$.store.book[?(@.price > 20)] | Books where price > 20 | 2 books |
$.store.book[?(@.category == 'fiction')] | Books in fiction category | 2 books |
$.store.book[-1:].title | Last book’s title | "Harry Potter" |
$.store.book.length() | Number of books | 3 |
🧪 JSONPath in RestAssured
✅ Example 1: Extract a value
Response res = given()
.when().get("https://reqres.in/api/users/2");
String email = res.jsonPath().getString("data.email");
System.out.println(email);
✅ Example 2: Extract nested values from JSON array
Response res = given().get("https://reqres.in/api/users?page=2");
List<String> emails = res.jsonPath().getList("data.email");
System.out.println(emails);
✅ Example 3: Conditional extraction
List<String> names = res.jsonPath()
.getList("data.findAll { it.id > 10 }.first_name");
System.out.println(names);
👉 Here findAll { it.id > 10 } acts like a filter, returning all objects where id > 10.
🧮 JSONPath Operators
| Operator | Meaning | Example |
@ | Current node | @.price |
==, != | Equal / Not equal | @.category == 'fiction' |
<, <=, >, >= | Comparisons | @.price > 20 |
&&, ` | ` | |
?() | Filter expression | [?(@.price < 30)] |
🔍 JSONPath vs XPath (Quick Comparison)
| Feature | JSONPath | XPath |
| Data Format | JSON | XML |
| Root Symbol | $ | / |
| Arrays | [] | [index] |
| Recursive Search | .. | // |
| Filter | [?()] | [condition] |
💼 JSONPath in Real API Automation
Example API Response:
{
"data": [
{ "id": 1, "name": "John", "role": "Tester" },
{ "id": 2, "name": "David", "role": "Developer" }
]
}
✅ Get all names:
List<String> names = response.jsonPath().getList("data.name");
✅ Get name of user where id = 2:
String name = response.jsonPath().getString("data.find { it.id == 2 }.name");
🧪 Advanced Use — JSONPath Validation in RestAssured
given()
.when().get("/users")
.then()
.body("data.find { it.id == 2 }.email", equalTo("janet.weaver@reqres.in"))
.body("data.size()", greaterThan(0))
.body("data.email", hasItem("janet.weaver@reqres.in"));
⚡ JSONPath + Groovy Expressions (Used Inside RestAssured)
RestAssured uses Groovy syntax, so you can apply filters like:
| Expression | Meaning |
find { it.id == 1 } | First match |
findAll { it.price > 20 } | All matches |
collect { it.name } | Collect all names |
sum { it.price } | Sum of prices |
max { it.price } | Maximum value |
Example:
float maxPrice = response.jsonPath().getFloat("store.book.max { it.price }.price");
System.out.println("Max Price: " + maxPrice);
🧩 Practice Tasks
Extract all “fiction” book titles from given JSON.
Find the highest-priced book using JSONPath.
Get the first user whose email contains “gmail.com”.
Count total books having price > 20.
Validate JSON response fields using JSONPath in RestAssured.
Would you like me to give a practice JSON + JSONPath exercise set (with real API responses and expected outputs)?
It’ll help you master filtering, array handling, and conditional queries used in interviews.
You said:
now give same for xml
ChatGPT said:
Excellent — let’s now cover XML and XPath, just like we did for JSON and JSONPath.
This is very important for API (SOAP) testing, data validation, and automation frameworks.
🧩 XML & XPath Tutorial (Complete Guide for Testers)
💡 What is XML?
XML (eXtensible Markup Language) is a markup language used to store and transport structured data.
It’s similar to HTML, but it describes data rather than displaying it.
Example:
<store>
<book category="fiction">
<title>The Alchemist</title>
<author>Paulo Coelho</author>
<price>12.99</price>
</book>
<book category="programming">
<title>Java Basics</title>
<author>James Gosling</author>
<price>25.50</price>
</book>
</store>
⚙️ XML Basics
| Concept | Description | Example |
| Tag | Defines start and end of element | <book> ... </book> |
| Attribute | Key-value inside start tag | <book category="fiction"> |
| Element | Data enclosed in tags | <title>Java</title> |
| Root Element | The top-level parent | <store> |
| Nested Elements | Elements inside another | <book><title>...</title></book> |
🧠 Well-formed XML Rules
Must have one root element
Every start tag must have a closing tag
Tags are case-sensitive
Attributes must be quoted
No overlapping tags (like
<a><b></a></b>❌)
🧩 XML vs JSON
| Feature | XML | JSON |
| Format | Tag-based | Key-value |
| Readability | Verbose | Compact |
| Data types | Text only | Supports numbers, booleans |
| Comments | Allowed | Not allowed |
| Schema validation | XSD | JSON Schema |
🧪 XPath — XML Query Language
XPath (XML Path Language) is used to navigate XML documents and extract specific elements or attributes.
Think of it as JSONPath for XML.
⚙️ XPath Syntax
| Symbol | Meaning | Example | Output |
/ | Select root or direct child | /store/book/title | All titles |
// | Select from anywhere (recursive) | //price | All prices |
@ | Select attribute | //book/@category | All categories |
[] | Filter (index or condition) | //book[1]/title | First title |
text() | Get element text | //title/text() | Text value |
* | Wildcard (any element) | //book/* | All child nodes |
🔍 XPath Examples
| XPath Expression | Description | Output |
/store/book/title | All book titles under store | Titles |
//book/title | Titles of all books | Titles |
//book[1]/title | Title of first book | “The Alchemist” |
//book[last()]/title | Title of last book | “Java Basics” |
//book[@category='fiction']/title | Titles of fiction books | “The Alchemist” |
//book[price>20]/title | Books with price > 20 | “Java Basics” |
count(//book) | Number of books | 2 |
🧩 XPath Operators
| Operator | Description | Example |
= | Equal | @category='fiction' |
!= | Not equal | @category!='fiction' |
<, >, <=, >= | Comparison | price>20 |
and, or | Logical | @category='fiction' and price>10 |
position() | Position in list | //book[position()=2] |
last() | Last element | //book[last()] |
🧪 XPath in RestAssured (XML API Testing)
✅ Example 1: Verify single element
given()
.when()
.get("https://example.com/books.xml")
.then()
.body("store.book[0].title", equalTo("The Alchemist"));
✅ Example 2: Using XMLPath
Response res = given()
.when()
.get("https://example.com/books.xml");
String title = res.xmlPath().getString("store.book[0].title");
System.out.println(title);
✅ Example 3: Extract attribute
String category = res.xmlPath().getString("store.book[0].@category");
System.out.println(category); // fiction
🧩 Advanced XPath Queries
| Expression | Meaning |
//book[contains(title,'Java')] | Books with title containing “Java” |
//book[starts-with(author,'P')] | Authors starting with “P” |
//book[price>10 and price<30] | Books priced between 10–30 |
| `//book/title | //bicycle/color` |
//book[not(@category='fiction')] | Non-fiction books |
🧮 XPath Functions
| Function | Description | Example |
count() | Count nodes | count(//book) |
sum() | Sum of numeric nodes | sum(//price) |
contains() | Substring match | contains(title,'Java') |
starts-with() | Prefix match | starts-with(author,'P') |
text() | Return text | //book/title/text() |
🧰 XML Validation in RestAssured
✅ Validate XML Schema (XSD)
import static io.restassured.module.jsv.XmlSchemaValidator.matchesXsdInClasspath;
given()
.when()
.get("/books.xml")
.then()
.body(matchesXsdInClasspath("booksSchema.xsd"));
🧩 XML Parsing in Java
➤ Using DOM Parser
import javax.xml.parsers.*;
import org.w3c.dom.*;
File file = new File("books.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
NodeList list = doc.getElementsByTagName("book");
System.out.println("Books count: " + list.getLength());
➤ Using XPath in Java
import javax.xml.xpath.*;
import org.w3c.dom.*;
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
String expr = "//book[@category='fiction']/title/text()";
String title = xpath.evaluate(expr, doc);
System.out.println(title);
🧩 Common XML Interview Questions
What is XML and how is it different from HTML/JSON?
What is XPath and how is it used in RestAssured?
How to extract XML attributes using XPath?
How to validate XML Schema in automation?
Write XPath to select the last node or filter by value.
How to handle SOAP response in API automation?
🧠 Practice Tasks
Write XPath to get the 2nd
<book>title.Get the category attribute for all books.
Extract all book titles where price > 20.
Count total
<book>nodes.Validate XML response against an XSD schema.
Would you like me to now create a practice-based XML + XPath exercise set (with sample XML responses and questions like extract, filter, and validate — just like a mini project for RestAssured)?
You said:
give full diferences
ChatGPT said:
Perfect — here’s a complete comparison of JSON vs XML with every key difference clearly explained from a tester’s and automation engineer’s perspective (especially for API testing using RestAssured / Postman).
🧩 JSON vs XML — Full Comparison Table
| Category | JSON (JavaScript Object Notation) | XML (eXtensible Markup Language) |
| Definition | Lightweight data-interchange format | Markup language used to describe structured data |
| Structure Type | Key–Value pairs | Tag-based hierarchical structure |
| Syntax Example | { "name": "Shree", "age": 30 } | <person><name>Shree</name><age>30</age></person> |
| Root Element | Optional | Mandatory — XML must have one root element |
| Readability | Compact and easier to read | Verbose and harder to read due to nested tags |
| Data Representation | Uses objects {} and arrays [] | Uses nested elements <tag> and attributes |
| Data Types Supported | String, Number, Boolean, Null, Array, Object | Text only (all values are strings) |
| Schema Validation | JSON Schema (.json file) | XML Schema (XSD file) |
| Attribute Support | Doesn’t support attributes; everything is key–value | Supports attributes inside tags (<book category="fiction">) |
| Comments | Not allowed in standard JSON | Allowed using <!-- comment --> |
| Namespaces | Not supported | Fully supports namespaces |
| Order Sensitivity | Order usually doesn’t matter | Order can be significant in XML |
| Metadata Representation | No built-in mechanism | Attributes provide metadata |
| Data Interchange | Commonly used for REST APIs | Commonly used for SOAP APIs |
| Parsing Speed | Faster (lightweight) | Slower (more complex structure) |
| File Size | Smaller (compact format) | Larger due to tag redundancy |
| Data Types Flexibility | Supports native data types directly | All data is stored as text and needs conversion |
| Support in Web APIs | Used in almost all RESTful services | Used mainly in older SOAP services |
| Parsing Tools in Java | Jackson, Gson, org.json, JSON.simple | DOM, SAX, StAX, JAXB parsers |
| Validation Tools | jsonschema validator | XSD validator |
| Data Access Path | JSONPath ($..price) | XPath (//price) |
| Mapping with Java Object | Easy with Jackson/Gson (POJO mapping) | More complex with JAXB (XML Binding) |
| Empty Values Representation | null | <tag></tag> or <tag/> |
| APIs Commonly Using It | REST APIs | SOAP APIs |
| Interoperability | Modern and widely accepted | Legacy systems still use XML |
| Human Friendliness | Easier to read and modify | More formal and structured |
| Error Handling | Simple (less strict syntax) | Strict (must be well-formed) |
| Extensibility | Limited | Highly extensible using tags |
| Best For | RESTful web services, configuration files | Document storage, SOAP, configuration, legacy systems |
💡 Quick Summary for Automation Testers
| Purpose | Prefer JSON | Prefer XML |
| REST API Testing | ✅ Yes | ❌ No |
| SOAP API Testing | ❌ No | ✅ Yes |
| Lightweight data transfer | ✅ Yes | ❌ No |
| Complex hierarchical document (with attributes) | ❌ No | ✅ Yes |
| Easy serialization/deserialization | ✅ Jackson / Gson | ⚙️ JAXB / DOM |
| Schema validation in automation | ✅ JSON Schema | ✅ XSD Schema |
| Fast parsing in RestAssured | ✅ jsonPath() | ✅ xmlPath() (but slower) |
⚙️ Code Example (Comparison in RestAssured)
JSON Example
Response res = given()
.contentType("application/json")
.body("{\"name\":\"Shree\", \"age\":30}")
.when()
.post("/createUser");
String name = res.jsonPath().getString("name");
XML Example
Response res = given()
.contentType("application/xml")
.body("<user><name>Shree</name><age>30</age></user>")
.when()
.post("/createUser");
String name = res.xmlPath().getString("user.name");
🧩 Interview-Focused Key Points
| Question | JSON Answer | XML Answer |
| What is it used for? | Data exchange in REST APIs | Data exchange in SOAP APIs |
| Supports comments? | ❌ No | ✅ Yes |
| Supports attributes? | ❌ No | ✅ Yes |
| Easy to map with Java objects? | ✅ Yes | ⚙️ Slightly complex |
| Supports array? | ✅ Yes ([]) | ⚙️ Must use repeated tags |
| Can validate structure? | ✅ JSON Schema | ✅ XSD |
| Preferred in automation frameworks? | ✅ Yes | ⚙️ Only for SOAP or legacy |
| Data navigation method? | JSONPath | XPath |
⚡ Conclusion
| Area | Winner |
| Simplicity | JSON ✅ |
| Readability | JSON ✅ |
| Flexibility | XML ✅ |
| Speed | JSON ✅ |
| Hierarchical complexity | XML ✅ |
| Modern API usage | JSON ✅ |
| Legacy system integration | XML ✅ |