In this tutorial, we’ll show you how to add values to a JSON object in Python. 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.
Python also contains built-in packages to handle JSON objects, making it easy to add or manipulate data in a JSON object.
Prerequisites
Make sure you have Python installed on your computer. If you haven’t already, you can download Python from the Python official website.
Step 1: Importing the JSON module
To work with JSON in Python, we need to import the json module. Here’s how you can do that:
1 |
import json |
Step 2: Creating a JSON object
To demonstrate how to add values to our JSON object, let’s create a simple JSON object:
1 2 3 4 5 |
json_object = { "name": "John", "age": 30, "city": "New York" } |
Step 3: Adding Values to JSON Object
To add a value to a JSON object in Python, you just need to assign a new value to a new key in your object. For instance, let’s add a new key “occupation” with a value “Engineer” to our object:
1 |
json_object['occupation'] = 'Engineer' |
Confirming the changes
Print the JSON object to confirm the changes:
1 |
print(json.dumps(json_object)) |
The output should be:
{ "name": "John", "age": 30, "city": "New York", "occupation": "Engineer" }
The Full Code
Here is the entire Python code used in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 |
import json json_object = { "name": "John", "age": 30, "city": "New York" } json_object['occupation'] = 'Engineer' print(json.dumps(json_object)) |
Conclusion
In conclusion, Python makes it very simple to work with JSON data. With just a few steps, you can add values to a JSON object in Python and modify JSON objects to fit your requirements.
As JSON continues to be used widely for data transmission due to its easy readability and simplicity, knowing how to manipulate JSON objects in Python will surely come in handy in your future projects.