Lesson · 40 min · Free
Python JSON Basics
Python JSON Basics body { font-family: sans-serif; line-height: 1.6; margin: 20px; } h1, h2 { color: #2c3e50; } pre { background-color: #ecf0f1; padding: 15px; border-radius: 5px; overflow-x: auto; white-space: pre-wrap;
Python JSON Basics
In the realm of pharmaceutical research, data exchange is paramount. Whether you're integrating with clinical trial databases, consuming data from public bioinformatics repositories, or exchanging information between different research groups, a standardized, human-readable, and machine-parsable format is crucial. JSON (JavaScript Object Notation) has emerged as a ubiquitous standard for this purpose, largely due to its simplicity and direct mapping to common data structures found in many programming languages, including Python. JSON is a lightweight data-interchange format. It is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. This makes JSON an ideal data-interchange language. Python has built-in support for JSON through its json module. This module allows you to easily convert Python objects into JSON strings (a process called "serialization" or "encoding") and convert JSON strings back into Python objects (a process called "deserialization" or "decoding"). Understanding this module is fundamental for any pharmaceutical researcher working with modern data pipelines.
Working with JSON in Python
The core functions you'll use from the json module are json.dumps() and json.loads() . The json.dumps() function takes a Python dictionary or list and converts it into a JSON formatted string. The json.loads() function does the opposite: it takes a JSON formatted string and parses it into a Python dictionary or list. Let's consider an example relevant to pharmaceutical research: representing data for a drug compound. We might have properties like the compound's name, chemical formula, molecular weight, and a list of known side effects. In Python, this would naturally be represented as a dictionary. import json # Python dictionary representing a drug compound drug_data = { "compound_name": "Ibuprofen", "chemical_formula": "C13H18O2", "molecular_weight": 206.28, "therapeutic_class": "Nonsteroidal Anti-inflammatory Drug (NSAID)", "known_side_effects": ["nausea", "heartburn", "dizziness"], "is_approved": True, "clinical_trials": [ {"id": "NCT000001", "phase": "Phase III", "status": "Completed"}, {"id": "NCT000002", "phase": "Phase II", "status": "Active"} ] } # Serialize the Python dictionary to a JSON formatted string json_string = json.dumps(drug_data, indent=4) # indent for pretty-printing print("--- JSON String Representation ---") print(json_string) print("\nType of json_string:", type(json_string)) # Now, let's deserialize a JSON string back into a Python object json_from_external_source = """ { "patient_id": "P001", "medication_history": [ {"drug": "Paracetamol", "dose_mg": 500, "start_date": "2023-01-15"}, {"drug": "Amoxicillin", "dose_mg": 250, "start_date": "2023-03-01"} ], "allergies": ["penicillin"], "current_status": "stable" } """ # Deserialize the JSON string patient_record = json.loads(json_from_external_source) print("\n--- Deserialized Python Dictionary ---") print(patient_record) print("Type of patient_record:", type(patient_record)) print("Patient ID:", patient_record["patient_id"]) print("First medication:", patient_record["medication_history"][0]["drug"]) As you can see from the example, json.dumps() converts the Python dictionary into a string, and json.loads() converts a string back into a Python dictionary. The indent=4 argument in json.dumps() is particularly useful for making the output JSON string human-readable by adding indentation, which is excellent for debugging and inspection, though it adds to the string's length. It's important to note the mapping between Python types and JSON types: Python dict JSON object Python list JSON array Python str JSON string Python int , float JSON number Python True JSON true Python False JSON false Python None JSON null This direct correspondence is what makes JSON so intuitive for Python developers.
Reading and Writing JSON Files
Often, JSON data will be stored in files rather than being hardcoded as strings. The json module provides json.dump() and json.load() for directly working with file objects. These functions are similar to their s -suffixed counterparts but handle file I/O automatically. import json # Data to be written to a JSON file clinical_trial_summary = { "trial_id": "CT_005", "drug_candidate": "Molecule X", "enrollment_target": 500, "current_enrollment": 320, "primary_endpoint": "Reduction in biomarker Y", "investigators": ["Dr. Smith", "Dr. Jones"], "status": "Recruiting" } # Write the data to a JSON file file_name = "clinical_trial_data.json" with open(file_name, 'w') as f: json.dump(clinical_trial_summary, f, indent=4) # Use indent for readability print(f"Data successfully written to {file_name}") # Now, let's read the data back from the JSON file loaded_data = {} with open(file_name, 'r') as f: loaded_data = json.load(f) print(f"\n--- Data loaded from {file_name} ---") print(loaded_data) print("Trial ID from loaded data:", loaded_data["trial_id"]) When writing, json.dump() takes the Python object and a file object as arguments. When reading, json.load() takes a file object and returns the deserialized Python object. Always remember to open files in the correct mode ('w' for write, 'r' for read).
Key Takeaways
JSON is a lightweight, human-readable data-interchange format, widely used in pharmaceutical research for data exchange. Python's built-in json module provides functionalities for working with JSON data. json.dumps() serializes a Python object (like a dict or list) into a JSON formatted string. json.loads() deserializes a JSON formatted string back into a Python object. json.dump() writes a Python object directly to a JSON file. json.load() reads a JSON file and deserializes its content into a Python object. Understanding the mapping between Python and JSON data types is crucial.
Practice Exercise
Imagine you have collected some preliminary data on a new experimental drug, "TheraMax." This data includes its molecular formula, target receptor, an efficacy score (out of 10), and a list of preliminary observations (e.g., "rapid absorption," "mild headache"). Create a Python dictionary to represent this data. Then, using the json module, convert this dictionary into a JSON formatted string and print it to the console. Finally, write this JSON string to a file named theramax_data.json .
Watch the full lesson — free
This topic is part of Python for Pharmaceutical Research, a complete AI-narrated video course. Press play once and watch the entire lecture like a movie.
Start the course free →