xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Working with JSON

More Python9 min readLesson 5 of 7

5.1 JSON is text, not a Python value

JSON is a text format for structured data, used by APIs and config files. json.loads parses text into Python values: objects become dicts, arrays become lists, strings stay strings, and numbers become int or float. json.dumps goes the other way.

JSON has no tuples, sets or comments. A dict with non-string keys will be converted or rejected, so keep keys as strings when the data crosses a language boundary.

python
import json

raw = '{"topic": "dictionaries", "minutes": 9}'
lesson = json.loads(raw)
print(lesson["topic"], lesson["minutes"])

lesson["minutes"] = 10
print(json.dumps(lesson))

Output

dictionaries 9
{"topic": "dictionaries", "minutes": 10}

json.load and json.dump work with file objects. A missing key raises KeyError, so use data.get("key", fallback) when the response shape is not guaranteed. Validation is a separate step; an API can return valid JSON that does not fit your expectations.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between json.load and json.loads?

    load reads from a file object; loads reads from a string you already have.

  • 02Why did my tuple become a list?

    JSON has arrays, not tuples. Decoding produces lists, so convert explicitly if the tuple matters.