Concepts / Introduction to XML

Introduction to XML

Both JSON and XML can represent structured information, but reaching a value is not equally direct.

  • Programming
Interactive lab

Try it: Parsing JSON into Python

How json.loads() reads JSON text token by token and builds Python dicts, lists, strings, numbers, True/False and None, how an access path like data["users"][0]["name"] walks that structure, and what json.dumps() writes back.

How it works

  1. The scanner reads the next token: a brace or bracket, a string in double quotes, a number, true / false / null, or a ',' / ':' delimiter.
  2. '{' starts a Python dict and '[' a list; both are pushed on a parse stack until their closing '}' or ']'.
  3. Inside a dict every key must be a double-quoted string followed by ':' and a value; items are separated by ','.
  4. Anything else stops the parse with JSONDecodeError, reporting the message, line, column and character position.
  5. The access path is applied one subscript at a time: dicts take keys (KeyError if missing), lists take integer indexes (IndexError if out of range).
  6. json.dumps() turns the Python objects back into JSON text (True → true, None → null), optionally indented.

Default run (43 steps): json.loads() receives 105 characters of text. The scanner starts at char 0 and reads one token at a time. … json.dumps(data, indent=2) turns the Python objects back into JSON text (171 characters): True → true, None → null, and strings get double quotes.

Simplified: Written from scratch to match CPython 3.12's json module (messages and positions checked against it); input is limited to 400 characters and 24 nesting levels, and the access path accepts only ["key"] and [index] subscripts. Python 3.13 reports a trailing comma in an object with a different message.

Educational simulation

Loading the simulation…

From Text to Usable Data

A JSON response begins as text, but working with that text directly would make data extraction inconvenient. The important boundary is json.loads(). It converts the JSON string into native Python data structures: dictionaries for JSON objects and lists for JSON arrays. After that conversion, the data can be accessed with ordinary Python indexing and iteration patterns rather than additional library calls for navigation.

JSON stringtext representationjson.loads()conversion stepPython datadictionary or listinputreturns
What changes before and after json.loads(), and when does the data become directly accessible?
Key point

The direct Python representation is the central idea: parsing changes the JSON string into a structure that Python can access immediately.

Nested Python Structures

A JSON object becomes a Python dictionary, so its named data is reached through dictionary keys. A JSON array becomes a Python list, so its items are reached through list indexes. When objects and arrays are nested, the resulting Python structure is nested too. You follow the structure one level at a time: use a key when the current value is a dictionary and use an index when the current value is a list.

Python dictionaryprofilenameAdaPythonindex 0skillsPython listXMLindex 1keykeyindexindex
What does a JSON structure become after json.loads(), and how are objects, arrays, keys, and values represented?
Code walkthrough
import json

data_text = '{"profile": {"name": "Ada", "skills": ["Python", "XML"]}}'
data = json.loads(data_text)
name = data["profile"]["name"]
second_skill = data["profile"]["skills"][1]
  1. 1
    data_text represents the JSON string before conversion.
  2. 2
    json.loads(data_text) returns a native Python structure and stores it in data.
  3. 3
    data["profile"] selects the nested object associated with the profile key.
  4. 4
    data["profile"]["name"] selects the value associated with the name key.
  5. 5
    data["profile"]["skills"] selects the list associated with the skills key.
  6. 6
    The final [1] selects the second item in that list.
Output
name: Ada
second_skill: XML

Following Keys and Indexes

Worked example

Extracting One Nested Value

Reach the second item in the skills list inside the profile object.

  1. 1
    Select the outer object

    Begin with the Python dictionary returned by json.loads(). Select the profile key to move into the nested object.

  2. 2
    Select the list

    From the profile dictionary, select the skills key. Its value is represented as a Python list.

  3. 3
    Select the item

    Apply the index 1 to the skills list. Python list indexing uses this index to reach the second item.

Result

The access path is data["profile"]["skills"][1]. It combines dictionary-key access with list-index access.

datadictionaryprofiledictionaryskillslistXMLindex 1["profile"]["skills"][1]
How does data move from a parsed JSON structure to a specific value when keys and indexes are applied in sequence?

JSON and XML Paths

Both JSON and XML can represent structured information, but reaching a value is not equally direct. Parsed JSON maps directly to Python dictionaries and lists, so extraction can use ordinary keys, indexes, and iteration patterns. XML has a self-descriptive structure and remains valuable when explicit semantic tagging or document-centric representation is important. However, the source material contrasts XML parsing with the simpler and more readable access made possible by JSON's direct Python mapping.

JSON stringXML documentPython dictionary orlistdirect mappingXML parsing andnavigationadditional pathKey and index accesscompact pathTarget datamore verbose routejson.loads()keys and indexesparse and navigatenavigation steps
What is the difference in the steps and code paths required to reach the same piece of data in parsed JSON versus parsed XML?
AspectJSONXML
Representation after parsingMaps directly to Python dictionaries and listsUses a self-descriptive, explicitly tagged structure
Data accessUses Python keys, indexes, and iteration patternsRequires more parsing and navigation steps
Code styleGenerally simpler and more readable for extractionGenerally more verbose for extraction
StrengthDirect mapping to common Python data typesSelf-descriptive and useful for document-centric applications

The comparison concerns extraction and representation, not whether one format is suitable for every application.

Why Web Services Prefer JSON

JSON became the industry standard for web services primarily because its structure maps directly to Python dictionaries and lists. That mapping lets a program parse the string and then use familiar indexing and iteration patterns immediately. The resulting extraction code is simpler and more readable than XML parsing code in the comparison described here.

This does not make XML useless. XML retains an advantage when a self-descriptive structure and explicit semantic tagging matter more than parsing simplicity, especially in document-centric applications. The practical choice depends on whether direct data consumption or richly explicit document structure is the stronger requirement.

JSONdirect Python mappingWeb servicessimple consumptionXMLself-descriptive structureDocument-centricapplicationsexplicit semantic taggingsupportssupports
Why is JSON widely used for web services while XML remains useful for self-descriptive and document-centric work?

Mistakes with Nested Access

  • Common mistake

    Treating the result of json.loads() as if it were still only raw text.

    What it looks like

    Continuing to search through the returned value as a string instead of using its dictionary keys and list indexes.

    Why it fails

    json.loads() converts the JSON string into native Python lists and dictionaries.

    Do this instead

    Inspect the structure conceptually and follow it with key access for dictionaries and index access for lists.

  • Common mistake

    Using a list index where a dictionary key is needed.

    What it looks like

    Trying to use a numeric position to reach the value under the profile key.

    Why it fails

    The profile value is reached through a dictionary key, not a list position.

    Do this instead

    Use the named key first, then use an index only after reaching a list.

  • Common mistake

    Using a dictionary key where a list index is needed.

    What it looks like

    Trying to select an item in skills with a name instead of a numeric index.

    Why it fails

    The skills value is represented as a Python list.

    Do this instead

    Use a list index such as 1 to select an item from that list.

  • Common mistake

    Assuming XML and JSON offer the same extraction path.

    What it looks like

    Expecting XML data to be reached through the same direct dictionary-and-list access used for parsed JSON.

    Why it fails

    The source comparison identifies XML parsing and navigation as more involved and verbose.

    Do this instead

    Choose the access approach that matches the representation and recognize JSON's direct Python mapping as its main convenience.

Practice the Access Path

EASY

Suppose json.loads() has returned a Python dictionary with a key named account. The value under account is another dictionary with a key named alerts. The value under alerts is a list, and the list contains three strings. Describe the sequence of keys and the list index you would use to reach the third alert.

Hints
  • Begin with the outer dictionary.
  • Use a key for account and then a key for alerts.
  • The third list item uses index 2.
Worked example

Practice Result

Reach the third alert in the nested alerts list.

  1. 1
    Enter account

    Use the account dictionary key.

  2. 2
    Enter alerts

    Use the alerts dictionary key inside account.

  3. 3
    Select the third item

    Use list index 2 to select the third item.

Result

The access pattern is data["account"]["alerts"][2].

Key Takeaways

  1. 1
    json.loads() converts a JSON string into native Python dictionaries and lists.
  2. 2
    Parsed JSON can be accessed directly with dictionary keys, list indexes, and iteration patterns.
  3. 3
    Nested extraction is a sequence of accesses: use keys for dictionaries and indexes for lists.
  4. 4
    JSON is widely used for web services because its direct Python mapping makes consumption simpler and more readable than XML parsing.
  5. 5
    XML remains valuable when self-descriptive structure and explicit semantic tagging are more important than parsing simplicity.

At a glance

  • json.loads() changes JSON text into Python dictionaries and lists.
  • Dictionary keys and list indexes provide a direct route to nested parsed JSON values.
  • JSON extraction is generally less verbose and simpler to read than XML parsing and navigation.
  • JSON's direct mapping to common Python data structures supports its widespread use in web services.
  • XML remains useful for self-descriptive and document-centric applications.

Related concepts

More concepts starting with I