Introduction to XML
Both JSON and XML can represent structured information, but reaching a value is not equally direct.
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
- The scanner reads the next token: a brace or bracket, a string in double quotes, a number, true / false / null, or a ',' / ':' delimiter.
- '{' starts a Python dict and '[' a list; both are pushed on a parse stack until their closing '}' or ']'.
- Inside a dict every key must be a double-quoted string followed by ':' and a value; items are separated by ','.
- Anything else stops the parse with JSONDecodeError, reporting the message, line, column and character position.
- 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).
- 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.
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.
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.
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
data_textrepresents the JSON string before conversion. - 2
json.loads(data_text)returns a native Python structure and stores it in data. - 3data["profile"] selects the nested object associated with the profile key.
- 4data["profile"]["name"] selects the value associated with the name key.
- 5data["profile"]["skills"] selects the list associated with the skills key.
- 6The final [1] selects the second item in that list.
name: Ada
second_skill: XMLFollowing Keys and Indexes
Extracting One Nested Value
Reach the second item in the skills list inside the profile object.
- 1Select the outer object
Begin with the Python dictionary returned by
json.loads(). Select the profile key to move into the nested object. - 2Select the list
From the profile dictionary, select the skills key. Its value is represented as a Python list.
- 3Select the item
Apply the index 1 to the skills list. Python list indexing uses this index to reach the second item.
The access path is data["profile"]["skills"][1]. It combines dictionary-key access with list-index access.
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.
| Aspect | JSON | XML |
|---|---|---|
| Representation after parsing | Maps directly to Python dictionaries and lists | Uses a self-descriptive, explicitly tagged structure |
| Data access | Uses Python keys, indexes, and iteration patterns | Requires more parsing and navigation steps |
| Code style | Generally simpler and more readable for extraction | Generally more verbose for extraction |
| Strength | Direct mapping to common Python data types | Self-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.
Mistakes with Nested Access
Common mistake Treating the result of json.loads() as if it were still only raw text.
What it looks likeContinuing to search through the returned value as a string instead of using its dictionary keys and list indexes.
Why it failsjson.loads()converts the JSON string into native Python lists and dictionaries.Do this insteadInspect 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 likeTrying to use a numeric position to reach the value under the profile key.
Why it failsThe profile value is reached through a dictionary key, not a list position.
Do this insteadUse 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 likeTrying to select an item in skills with a name instead of a numeric index.
Why it failsThe skills value is represented as a Python list.
Do this insteadUse 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 likeExpecting XML data to be reached through the same direct dictionary-and-list access used for parsed JSON.
Why it failsThe source comparison identifies XML parsing and navigation as more involved and verbose.
Do this insteadChoose the access approach that matches the representation and recognize JSON's direct Python mapping as its main convenience.
Practice the Access Path
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.
Practice Result
Reach the third alert in the nested alerts list.
- 1Enter account
Use the account dictionary key.
- 2Enter alerts
Use the alerts dictionary key inside account.
- 3Select the third item
Use list index 2 to select the third item.
The access pattern is data["account"]["alerts"][2].
Key Takeaways
- 1
json.loads()converts a JSON string into native Python dictionaries and lists. - 2Parsed JSON can be accessed directly with dictionary keys, list indexes, and iteration patterns.
- 3Nested extraction is a sequence of accesses: use keys for dictionaries and indexes for lists.
- 4JSON is widely used for web services because its direct Python mapping makes consumption simpler and more readable than XML parsing.
- 5XML 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.