Skip to main content

Command Palette

Search for a command to run...

Xml & Json

Published
•15 min read•View as Markdown

🧩 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

ConceptDescriptionExample
ObjectCollection of key-value pairs inside {}{ "name": "John", "age": 30 }
ArrayOrdered list of values inside [][ "apple", "banana", "cherry" ]
KeyAlways a string, wrapped in quotes"name"
ValueCan be string, number, object, array, boolean, or null"John", 30, true, null
CommaSeparates 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

TypeExample
String"Hello"
Number25, 3.14
Booleantrue / false
Nullnull
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)

ExpressionDescriptionExample Output
store.book[0].titleGet title of first book“Java Basics”
store.book[-1].priceGet last book’s price30.5
store.book.find { it.price > 10 }Find book where price > 10Object
store.book.size()Count books3

🚀 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

ErrorReasonFix
Missing quotesKeys must be in quotes"name": "John"
Trailing commaLast pair shouldn’t end with commaRemove comma
Invalid nestingBraces/Brackets mismatchCheck {} and [] balance

💡 10. Practice Tasks

  1. Create JSON for Employee → name, id, skills[], address{}

  2. Parse JSON and extract nested values

  3. Convert List of POJOs to JSON array using Jackson

  4. Validate JSON response schema in RestAssured

  5. 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

SymbolMeaningExampleOutput
$Root element$whole JSON
.Child operator$.store.bookall books
[]Array index$.store.book[0]1st book
*Wildcard (all elements)$.store.book[*].titleall book titles
..Recursive search$..priceall prices
@Current element$.store.book[?(@.price > 20)]books with price > 20

🧠 Examples

ExpressionDescriptionOutput
$.store.book[0].titleTitle of 1st book"The Alchemist"
$.store.book[*].priceAll book prices[12.99, 25.50, 30.00]
$..priceAll prices (book + bicycle)[12.99, 25.50, 30.00, 120.50]
$.store.book[?(@.price > 20)]Books where price > 202 books
$.store.book[?(@.category == 'fiction')]Books in fiction category2 books
$.store.book[-1:].titleLast book’s title"Harry Potter"
$.store.book.length()Number of books3

🧪 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

OperatorMeaningExample
@Current node@.price
==, !=Equal / Not equal@.category == 'fiction'
<, <=, >, >=Comparisons@.price > 20
&&, ``
?()Filter expression[?(@.price < 30)]

🔍 JSONPath vs XPath (Quick Comparison)

FeatureJSONPathXPath
Data FormatJSONXML
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:

ExpressionMeaning
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

  1. Extract all “fiction” book titles from given JSON.

  2. Find the highest-priced book using JSONPath.

  3. Get the first user whose email contains “gmail.com”.

  4. Count total books having price > 20.

  5. 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

ConceptDescriptionExample
TagDefines start and end of element<book> ... </book>
AttributeKey-value inside start tag<book category="fiction">
ElementData enclosed in tags<title>Java</title>
Root ElementThe top-level parent<store>
Nested ElementsElements inside another<book><title>...</title></book>

🧠 Well-formed XML Rules

  1. Must have one root element

  2. Every start tag must have a closing tag

  3. Tags are case-sensitive

  4. Attributes must be quoted

  5. No overlapping tags (like <a><b></a></b> ❌)


🧩 XML vs JSON

FeatureXMLJSON
FormatTag-basedKey-value
ReadabilityVerboseCompact
Data typesText onlySupports numbers, booleans
CommentsAllowedNot allowed
Schema validationXSDJSON 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

SymbolMeaningExampleOutput
/Select root or direct child/store/book/titleAll titles
//Select from anywhere (recursive)//priceAll prices
@Select attribute//book/@categoryAll categories
[]Filter (index or condition)//book[1]/titleFirst title
text()Get element text//title/text()Text value
*Wildcard (any element)//book/*All child nodes

🔍 XPath Examples

XPath ExpressionDescriptionOutput
/store/book/titleAll book titles under storeTitles
//book/titleTitles of all booksTitles
//book[1]/titleTitle of first book“The Alchemist”
//book[last()]/titleTitle of last book“Java Basics”
//book[@category='fiction']/titleTitles of fiction books“The Alchemist”
//book[price>20]/titleBooks with price > 20“Java Basics”
count(//book)Number of books2

🧩 XPath Operators

OperatorDescriptionExample
=Equal@category='fiction'
!=Not equal@category!='fiction'
<, >, <=, >=Comparisonprice>20
and, orLogical@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

ExpressionMeaning
//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

FunctionDescriptionExample
count()Count nodescount(//book)
sum()Sum of numeric nodessum(//price)
contains()Substring matchcontains(title,'Java')
starts-with()Prefix matchstarts-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

  1. What is XML and how is it different from HTML/JSON?

  2. What is XPath and how is it used in RestAssured?

  3. How to extract XML attributes using XPath?

  4. How to validate XML Schema in automation?

  5. Write XPath to select the last node or filter by value.

  6. How to handle SOAP response in API automation?


🧠 Practice Tasks

  1. Write XPath to get the 2nd <book> title.

  2. Get the category attribute for all books.

  3. Extract all book titles where price > 20.

  4. Count total <book> nodes.

  5. 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

CategoryJSON (JavaScript Object Notation)XML (eXtensible Markup Language)
DefinitionLightweight data-interchange formatMarkup language used to describe structured data
Structure TypeKey–Value pairsTag-based hierarchical structure
Syntax Example{ "name": "Shree", "age": 30 }<person><name>Shree</name><age>30</age></person>
Root ElementOptionalMandatory — XML must have one root element
ReadabilityCompact and easier to readVerbose and harder to read due to nested tags
Data RepresentationUses objects {} and arrays []Uses nested elements <tag> and attributes
Data Types SupportedString, Number, Boolean, Null, Array, ObjectText only (all values are strings)
Schema ValidationJSON Schema (.json file)XML Schema (XSD file)
Attribute SupportDoesn’t support attributes; everything is key–valueSupports attributes inside tags (<book category="fiction">)
CommentsNot allowed in standard JSONAllowed using <!-- comment -->
NamespacesNot supportedFully supports namespaces
Order SensitivityOrder usually doesn’t matterOrder can be significant in XML
Metadata RepresentationNo built-in mechanismAttributes provide metadata
Data InterchangeCommonly used for REST APIsCommonly used for SOAP APIs
Parsing SpeedFaster (lightweight)Slower (more complex structure)
File SizeSmaller (compact format)Larger due to tag redundancy
Data Types FlexibilitySupports native data types directlyAll data is stored as text and needs conversion
Support in Web APIsUsed in almost all RESTful servicesUsed mainly in older SOAP services
Parsing Tools in JavaJackson, Gson, org.json, JSON.simpleDOM, SAX, StAX, JAXB parsers
Validation Toolsjsonschema validatorXSD validator
Data Access PathJSONPath ($..price)XPath (//price)
Mapping with Java ObjectEasy with Jackson/Gson (POJO mapping)More complex with JAXB (XML Binding)
Empty Values Representationnull<tag></tag> or <tag/>
APIs Commonly Using ItREST APIsSOAP APIs
InteroperabilityModern and widely acceptedLegacy systems still use XML
Human FriendlinessEasier to read and modifyMore formal and structured
Error HandlingSimple (less strict syntax)Strict (must be well-formed)
ExtensibilityLimitedHighly extensible using tags
Best ForRESTful web services, configuration filesDocument storage, SOAP, configuration, legacy systems

💡 Quick Summary for Automation Testers

PurposePrefer JSONPrefer 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

QuestionJSON AnswerXML Answer
What is it used for?Data exchange in REST APIsData 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?JSONPathXPath

⚡ Conclusion

AreaWinner
SimplicityJSON ✅
ReadabilityJSON ✅
FlexibilityXML ✅
SpeedJSON ✅
Hierarchical complexityXML ✅
Modern API usageJSON ✅
Legacy system integrationXML ✅