Python Convert String to JSON

1. Introduction

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It's commonly used for transmitting data in web applications and for configuration files. Python provides built-in support for JSON with its json module, allowing for easy conversion between JSON encoded data and Python objects. This blog post demonstrates how to convert a JSON formatted string into a Python dictionary using the json module.

Definition

Converting a string to JSON in Python involves taking a string that is formatted in JSON and transforming it into a Python object (usually a dictionary). The json module in Python provides a method called loads() (short for "load string") that can be used for this conversion.

2. Program Steps

1. Import the json module.

2. Have or receive a string that is formatted in JSON.

3. Use the json.loads() method to parse the JSON string into a Python dictionary.

4. Use or manipulate the dictionary as needed in your Python program.

3. Code Program

# Step 1: Import the json module
import json

# Step 2: Define a JSON formatted string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Step 3: Parse the JSON string into a Python dictionary
person_dict = json.loads(json_string)

# Step 4: Output the dictionary to verify the conversion
print(person_dict)

Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

Explanation:

1. The json module is imported which provides functions for handling JSON data.

2. json_string contains a string with JSON data representing a person's name, age, and city.

3. person_dict is created by using the json.loads() function to convert json_string into a Python dictionary.

4. The print statement is used to output person_dict, confirming that the conversion has taken place and the string is now a Python dictionary with the keys and values extracted from the JSON string.


Comments