Lesson guide
What this Python exercise practices
Parse JSON into Python objects is a beginner practice lesson that focuses on functions, parameters, return values. It is designed to be solved in about 6 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- Function parameters
- Return values
Difficulty and time
- Level
- Beginner
- Estimated time
- 6 minutes
Related public exercises
Summary
Use the json module to convert a JSON string into Python objects safely.
Problem statement
Given a string containing JSON data, parse it into the corresponding Python object using the json module. If the input is not valid JSON, return None. Your function should handle JSON objects, arrays, strings, numbers, booleans, and null.
Task
Write a function that parses a JSON string and returns the equivalent Python object, returning None for invalid JSON.
Examples
Parse a JSON object
Input
parse_json('{"a": 1, "b": [1,2]}')
Output
{'a': 1, 'b': [1, 2]}
Explanation
A JSON object becomes a Python dict; arrays become lists.
Input format
A single argument: json_str (string) containing JSON.
Output format
Return the parsed Python object (dict/list/str/int/float/bool/None). Return None if input is not valid JSON.
Constraints
Do not use eval. Use Python's json module and handle JSONDecodeError. Keep behavior deterministic.
Samples
Sample input 0
parse_json('[1, 2, 3]')
Sample output 0
[1, 2, 3]
Explanation 0
A JSON array becomes a Python list.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.