This article provides a detailed guide to the Difference Between JSON and XML With Example. It covers how both formats represent the same data, where each one is used, and what to check before choosing a format for an API or data integration.
Have you ever wondered why an API response uses curly brackets while a supplier’s product feed contains opening and closing tags?
Imagine you run an online store that sells a steel water bottle for ₹499. Your mobile app needs the product’s name, price, stock status, and tags to display it correctly. Your distributor needs those same details for its nightly catalogue import, but its software expects an XML file.
This is where the difference between JSON and XML becomes practical. JSON represents information using objects, arrays, and values. XML uses elements, attributes, and text. For example, the app can receive “inStock”: true in JSON, while the distributor’s feed can contain <inStock>true</inStock> in XML.
The way each format represents a value can affect how the receiving system uses it. A JSON parser reads true as a Boolean. A basic XML parser reads the text inside <inStock>, and the schema or application determines how to interpret it. Your team also needs to agree on details such as whether 499 means rupees or paise and how to handle a missing price or an empty tag list.
Whether you are learning how APIs work, building a mobile app, or connecting your software to a supplier’s system, understanding these differences can help you choose a format and avoid errors when exchanging data.

In this Oflox® guide, we will compare the same product record in JSON and XML, read both formats in Python, and explain what to test before using either one in a real integration.
Let’s explore it together!
Table of Contents
Difference Between JSON and XML With Example
Let’s say an online store sells a steel water bottle for ₹499. The store needs to share five details with another application. These are the product ID, name, price, stock status, and catalogue tags.
Here’s how the same product record looks in JSON and XML.
1. JSON Example
{
"id": 101,
"name": "Steel Water Bottle",
"price": 499,
"inStock": true,
"tags": ["drinkware", "steel"]
}
The curly brackets {} enclose an object. Inside the object, each property has a name and a value. For example, prices is the name, and 499 is its value.
The square brackets [] enclose an array. In this example, the tags array contains two strings. Their order is preserved when the JSON is read.
Notice how the product name is inside double quotes, while 499 and true are written without quotes. The quotes are part of how JSON communicates the type of a value. A client can use 499 for a calculation and true for a stock check. If the server sends “499” or “true”, the client receives strings.
2. XML Example
<product>
<id>101</id>
<name>Steel Water Bottle</name>
<price>499</price>
<inStock>true</inStock>
<tags>
<tag>drinkware</tag>
<tag>steel</tag>
</tags>
</product>
The <product> element is the root of the document. The product details sit inside it as child elements. For example, <name> opens the name element and </name>closes it.
The <tags> element holds two <tag> children. The team designing this file has chosen repeated child elements to represent the list. The importer needs to know that every <tag> under <tags> belongs in the product’s tag list.
A basic parser reads the contents of <price> as text. The application can convert that text to an integer. An XML Schema Definition, or XSD, can also specify that the element must contain an integer and reject a value such as free.
3. What This Example Tells Us
Both versions carry the same product details. JSON shows the list directly through array syntax. XML expresses the list through the relationship between the <tags> container and its <tag> children.
There is also a detail that neither example explains by itself. Does 499 mean ₹499 or 499 paise? For this example, the store has agreed that price is in whole rupees. A real API should document that unit or include enough information in the record for the receiver to interpret the amount correctly.
What Is JSON?
JSON stands for JavaScript Object Notation. It is a text-based format that applications use to store or exchange structured data. A server written in PHP can send JSON to a mobile app, while a Python service can read the same format to prepare a report.
JSON works well when your data looks like a record, a collection of records, or a combination of the two. For example, an order can have a customer object, an array of line items, and a numeric total. The structure makes it easy to see which details belong together.
1. JSON Objects, Arrays, and Data Types
Here’s how the main parts of a JSON document work.
| JSON feature | Example | What it represents |
|---|---|---|
| Object | {“id”: 101} | A collection of named properties |
| Array | [“drinkware”, “steel”] | An ordered list of values |
| String | “Steel Water Bottle” | Text |
| Number | 499 | A numeric value |
| Boolean | true | A true or false value |
| Null | null | An explicit null value whose meaning the application defines |
JSON objects and arrays can be nested. A catalogue response, for instance, can contain a products array and a pagination object. The array holds the records, while the pagination object tells the client how to fetch the next set of products.
Some values need an additional convention. JSON has no dedicated date type, so a team might send a promised delivery date as “2026-12-04” and document that it is a calendar date. For an event timestamp, the team should also define how the time zone or offset is represented.
2. How JSON Became Popular
JSON’s notation comes from JavaScript. The format was adopted across other programming languages because it gives applications a common way to describe structured values. The IETF published an early JSON specification in 2006.
A product record illustrates why it is widely used in APIs. A frontend developer can read the record and quickly identify the price, availability, and tags. A backend developer can send the same structure from a service written in a different language.
3. Benefits and Challenges of JSON
- Straightforward representation of records. Objects group related fields and arrays represent lists directly.
- Clear value types. A reader can distinguish 499, “499”, and null without guessing from the field name.
- Convenient for web and mobile APIs. A response can map naturally to the models an application already uses.
- Support for schema validation. JSON Schema can define required properties, allowed values, and the shape of nested data.
- Additional rules for certain fields. Dates, units, large identifiers, and monetary precision need a documented convention. JSON syntax alone cannot tell you what a valid order is.
One simple mistake is storing a postal code or product identifier as a number when leading zeros have meaning. For example, “000101” retains all six characters. As a numeric ID, it would lose those leading zeros.
What Is XML?
XML stands for Extensible Markup Language. It uses named elements, attributes, and text to represent structured information. The format is extensible because an organisation can define a vocabulary for its own purpose, such as products, shipments, invoices, or articles.
The W3C published XML 1.0 as a Recommendation in February 1998. XML developed from SGML, an earlier markup standard. That background helps explain why XML can describe both business records and documents with headings, references, and formatting.
1. Elements and Attributes
An element can contain text or other elements. An attribute supplies a named value in the opening tag.
<product id="101">
<name>Steel Water Bottle</name>
<price currency="INR">499</price>
</product>
Here, the product ID is an attribute on <product>, while the name is a child element. The currency is an attribute on <price>. This layout is a design choice. If a supplier’s integration guide puts the ID in an <id> element, your exporter should follow that structure.
2. Namespaces and XML Schema
A namespace helps keep names distinct when one document combines multiple XML vocabularies. In an order feed, a catalogue’s status could mean whether an item is available. A carrier’s status could mean whether the parcel has been delivered. A namespace gives each field a distinct identity even when both use the local name status.
An XSD defines rules for an XML document. It can specify that a product must have an ID, that a price must be numeric, and that certain child elements must appear in a defined order.
3. Benefits and Challenges of XML
- Supports document content. An element can contain text alongside child elements for emphasis, citations, or other inline information.
- Has a standard namespace mechanism. Multiple vocabularies can appear in the same document with distinct names.
- Can enforce a detailed structure. An XSD can define required fields, acceptable types, and element order.
- Supports established integration formats. Examples include SOAP messages, XML sitemaps, and partner-defined file feeds.
- Requires careful attention to the contract. A file may be well-formed XML and still fail because the receiver expects a different namespace, element order, or attribute.
For example, <price>free</price>is well-formed XML. It would still fail against a schema that requires price to contain an integer. Being able to open a file is only the first check.
JSON vs XML Comparison Table
Here’s a quick comparison you can refer to when choosing a format for an API, document, or file exchange.
| Feature | JSON | XML |
|---|---|---|
| Full form | JavaScript Object Notation | Extensible Markup Language |
| Main building blocks | Objects, arrays, and values | Elements, attributes, and text |
| Top-level structure | Any valid JSON value, including an object or array | An XML document has one root element |
| List representation | Built-in array syntax | Commonly uses repeated child elements |
| Types | Built-in strings, numbers, Booleans, null, objects, and arrays | A schema or application can define how values are interpreted |
| Attributes | Related information is expressed through properties | Elements can carry attributes and child elements |
| Namespaces | The application can define naming conventions | XML defines a standard namespace mechanism |
| Ordering | Array order matters. Object property order is unsuitable for business rules | Child order is preserved and can be required by the schema |
| Comments | Standard JSON syntax has no comments | Supports XML comments |
| Validation | JSON Schema | XML Schema, commonly called XSD |
| Common HTTP media type | application/json | application/xml for generic XML |
| Typical use | Web APIs, mobile apps, webhooks, and structured records | SOAP, sitemaps, document markup, and partner feeds |
Key Differences Between JSON and XML
The table covers the features. Here’s how some of those differences affect the way you build and maintain an integration.
1. Syntax and Readability
JSON usually feels familiar when you are reading short application records. You can scan a product object and find the value beside its property name. XML repeats names in opening and closing tags, which adds length but makes the start and end of a section visible.
Think about what a person will be reading. A short product response is easy to scan as JSON. A publication document with paragraphs, footnotes, and inline emphasis may be easier to describe with XML elements that preserve the order of the text.
2. Empty, Missing, and Null Values
In JSON, an omitted description property, “description”: “”, and “description”: null are different cases. In XML, an omitted <description/> element is also different from an empty <description/> element. A schema can separately support a nil value with xsi:nil=”true” when the element allows it.
Imagine an inventory update where omitting the description means “keep the current text”, and sending an empty string means “clear the text”. A converter that treats both inputs as empty could erase descriptions across an entire catalogue. Write down the meaning of each case before building the import.
3. File Size and Parsing Speed
The compact UTF-8 versions of the product examples in this article take 94 bytes in JSON and 152 bytes in XML. This counts only the example data, with formatting whitespace removed and no trailing newline or XML declaration. Part of the difference comes from the closing tags in XML.
If performance matters, measure a representative file or response in your own application. When a server compresses responses, repeated text can compress well. Parser choice, schema checks, and loading an entire file into memory can also affect processing time. A small example demonstrates the effect of syntax on raw size. A realistic test tells you what your system will experience.
4. Structural Validation and Business Validation
Suppose a supplier sends a product with a price of -499. The value can be valid JSON and could pass a schema that checks only whether the price is a number. It still violates a store rule that prices must be non-negative.
Some rules can be added to a schema. Others need application logic. For example, checking whether a SKU has been discontinued requires access to the catalogue. When an import fails, it helps to know whether the file could not be parsed, a field failed validation, or a product failed a business rule.
How to Read JSON and XML in Python
Here’s a short exercise you can follow to see how Python reads the same values from the two formats.
1. Save the Product Files
Copy the JSON example into a file called product.json. Copy the XML example into product.xml. Save both files as UTF-8 in the same folder.
You can follow along with only these two files and Python’s standard library.
2. Read the JSON File
import json
from pathlib import Path
text = Path("product.json").read_text(encoding="utf-8")
product = json.loads(text)
print(product["name"])
print(product["price"], type(product["price"]).__name__)
print(product["inStock"], type(product["inStock"]).__name__)
print(product["tags"])
The output includes 499 int and True bool. Python also reads tags as a list. If you change 499 to “499” in the JSON file, the printed type becomes str. Try sorting several prices after such a change and you will see why the field type matters.
3. Read the XML File
from pathlib import Path
from xml.etree import ElementTree
text = Path("product.xml").read_text(encoding="utf-8")
root = ElementTree.fromstring(text)
product = {
"id": int(root.findtext("id")),
"name": root.findtext("name"),
"price": int(root.findtext("price")),
"inStock": {"true": True, "false": False}[root.findtext("inStock")],
"tags": [tag.text for tag in root.findall("tags/tag")],
}
print(product)
This example reads the local sample and maps its text values to Python types. The stock mapping accepts the two values defined for this sample, true and false. In a production importer, check required fields individually and include the product ID and field name in any error message.
4. Try a Few Changes
Change the record to contain one tag, then remove all tags. The application should receive a list in both cases. An empty JSON list is [], and this XML mapping reads an empty <tags/> container as an empty list.
Next, change the name to Steel & Glass. The ampersand can appear directly in a JSON string. In XML element text, write it as Steel & Glass; Glass. A serializer handles this escaping when it writes the document, which is one reason to use a library to generate files.
When Should You Use JSON or XML?
Here are a few practical situations that show how teams make the choice.
1. Use JSON for a New Web or Mobile API
Suppose you are building a website and Android app that share the same catalogue. A JSON response can give both applications the product name, price, stock status, and tags in a structure they can use directly.
Think about the older app versions too. Adding an optional field such as brand may be straightforward when clients accept additional properties. Changing price from a number to an object can break code that already uses it for calculations. Document how the API will evolve before making a change like that.
2. Use XML for an Integration With an XML Contract
Suppose a distributor supplies an XSD for a nightly inventory upload. It expects the SKU in an attribute, the quantity in a child element, and warehouse details in a specific order. Build the export to match that contract and validate it locally before sending the first feed.
Then use the distributor’s test import, if available. A file can pass XSD validation and still be rejected because the distributor does not recognise a warehouse code. A test with the actual receiver checks rules that a local schema may never see.
3. Use the Format Required by the Document or Protocol
SOAP messages use XML. An XML sitemap also follows a defined structure, including a root element and the sitemap namespace. In these cases, the format is part of what the receiver expects.
XML can also make sense in publishing. For example, <p>Use <em>cold </em>water.</p> stores the sentence together with the exact position of the emphasis. If you convert that paragraph, preserve the order of the text and the <em> element when the receiving workflow needs both.
4. Support Both When Clients Need Both
A company might have a dashboard that reads JSON and a partner system that reads XML. Both representations can come from the same product model. If the API uses content negotiation, the client can specify what it accepts through the Accept header, and the server can identify the returned format with Content-Type.
Keep stock and pricing rules in one place. If a discontinued product cannot be sold, both the JSON response and the XML feed should communicate that state consistently.
5+ Helpful JSON and XML Tools
Here are the tools you can use to inspect a response, validate a file, or document an API.
| Tool | Where it helps |
|---|---|
| jq | Formats JSON and extracts specific fields or items |
| xmllint | Checks XML syntax and validates a file against a local XSD |
| Python json and ElementTree | Read files and build field-by-field mappings |
| JSON Schema validator | Checks whether a payload meets an agreed JSON schema |
| Postman or curl | Inspects API requests, headers, status codes, and responses |
| VS Code | Makes it easier to inspect nested records and compare files |
| OpenAPI | Documents API media types and JSON or XML representations |
For a quick check, run jq ‘.tags’ product.json to inspect the JSON tag list. Run xmllint –noout product.xml to check XML syntax. If you have a trusted local schema, run xmllint –noout –schema product.xsd product.xml to validate the file against it.
If you are investigating a customer feed, reproduce the issue with a small anonymised sample. One failing product and a few relevant fields are usually enough to show whether the problem is in the file or in the importer.
Expert Tips and Common Mistakes
Here are the details worth checking before an API response or file exchange goes live.
1. Agree on Money and Identifier Types
Use a currency code when a system serves multiple currencies. If the contract represents money in minor units, ₹499.50 can be represented by 49950 paise alongside “INR” . If it uses a decimal string instead, specify the expected precision.
Use strings for identifiers when leading zeros or large digits must be preserved. An identifier is normally compared or looked up. You rarely need to perform arithmetic with it.
2. Keep Lists the Same Shape
Some XML-to-JSON converters return a single value when they see one child and an array when they see several. A frontend expecting an array might work for a bottle with two tags and fail for a mug with one.
Define the field as a list in the mapping and test zero, one, and several items. Include an absent list as a separate case when its meaning differs from an empty one.
3. Use a Parser and Serializer
Building a JSON string or XML document by joining pieces of text makes quotes, ampersands, and line breaks easy to mishandle. Pass your values to a standard serialization library so it can escape them correctly.
For external input, apply size and nesting limits appropriate to the integration. When accepting untrusted XML, review the parser’s settings and disable DTDs and external entity resolution unless the application needs them.
4. Give the Sender an Error They Can Fix
An error such as Invalid product file leaves the sender searching through the entire batch. Give them the record reference, field, and expected value when possible.
For example, “Product 101: price must be a non-negative integer in paise” tells the sender exactly which field to correct. Decide whether they should retry the whole file or resend only the failed records. That choice matters when a nightly import contains thousands of items.
FAQs:)
A. JSON represents data with objects, arrays, and values. XML represents data with elements, attributes, and text. A JSON tag list can look like [“steel”], while an XML contract can represent it as steel.
A. JSON represents records and lists in a form that applications can read easily. It also supports common types such as strings, numbers, Booleans, and arrays directly.
A. Speed depends on the payload, compression, parser, and validation steps. JSON often produces smaller raw files for simple records. Use your own data to measure which format performs better in your application.
A. Yes. Define how fields, lists, attributes, namespaces, and empty values map between the formats. For XML with inline markup, decide how the conversion will preserve text and element order.
A. Yes. An HTTP API can return XML when it supports that representation. Some APIs provide both JSON and XML and let clients request a supported media type.
A. An XML document can represent a list through repeated elements. An XSD or application rule can specify that a field contains a Boolean. JSON has dedicated syntax for arrays and built-in Boolean values.
A. Choose XML when a partner contract, SOAP service, sitemap, or document workflow requires it. XML is also useful when the data depends on namespaces or combines text with inline markup.
Conclusion:)
Understanding the difference between JSON and XML helps you choose a data format that fits the systems you need to connect. JSON works well for web and mobile APIs that exchange records such as products, orders, and customer details. XML fits integrations that depend on a defined document structure, namespaces, or an XML Schema (XSD).
Start with one record, such as the steel water bottle in this guide. Check whether the receiving system reads 499 as the intended price, treats true as a Boolean, and keeps a one-item tag list as a list. Then send a record with a missing price and check whether the error tells the sender which field to fix.
At Oflox®, we approach custom software and AI development by defining which fields each system needs, how it interprets those fields, and what happens when a record fails validation. Those decisions guide the integration whether we’re building a new JSON API or connecting to an existing XML feed.
“A data format earns its place when the receiving system can read the record correctly and tell you what to fix when it can’t.” — Suggested quote for Mr Rahman, Oflox®
Read also:)
- What Is an LLM Gateway? A-to-Z Guide for Beginners!
- What Is FastAPI in Python? A-to-Z Guide for Beginners!
- How to Compare Social Media Growth Services Before Buying?
Have you used JSON or XML in an API or data integration? Share which format you chose and what gave you the most trouble, whether it was a data type, a missing field, or a validation error.