- How to Convert a String to JSON in Python
- What Is a JSON File?
- Working with JSON Files in Python
- From JSON to Python Object: Deserializing
- From Python Object to JSON String: Serializing
- Creating a JSON File with dump()
- Printing in the Command Line
- Learn More About JSON and Python
- Python JSON – How to Convert a String to JSON
- What is JSON?
- Where is JSON used?
- Basic JSON syntax
- How to work with JSON data in Python
- Include the JSON module for Python
- Use the json.loads() function
- Conclusion
- Python Convert From Python to JSON
- Example
- Example
- Example
- Python JSON
- JSON in Python
- Example
- Parse JSON — Convert from JSON to Python
- Example
- Convert from Python to JSON
- Example
- Example
- Example
- Format the Result
- Example
- Example
- Order the Result
- Example
How to Convert a String to JSON in Python
JSON stands for JavaScript Object Notation. Although its name indicates that it is associated with the JavaScript programming language, the JSON format is language-independent and frequently used in many different programming languages.
What Is a JSON File?
JSON files are commonly used in transferring data between computers. For instance, when downloading a file from an API, you often need to deal with JSON files. Here is a great article that explains downloading a file in Python from an API.
The following is an example of a JSON file:
Files that store data in JSON format are called JSON files. These files are text-based, human-readable, and easy to process – all of which make them highly popular.
In this article, we will learn how to convert a string to JSON in Python and how to create JSON files from Python objects.
Working with JSON Files in Python
Python has a built-in library called json which provides simple and efficient methods for working with JSON files. Let’s go over some examples that demonstrate how to convert a string to JSON in Python and vice versa.
From JSON to Python Object: Deserializing
The following is a JSON string:
We can use the loads() method of the json library to convert this string to a Python object:
>>> import json >>> myobject = json.loads(example)
We have just converted JSON encoded data into a Python object. This process is called deserializing. The resulting Python object is a dictionary. A Python dictionary consists of key-value pairs and we can easily access its items using the keys. For example, if we want to access the FirstName in the myobject dictionary, we write:
If we have a JSON file and want to turn it into a Python object, we can use the load() method. Take a quick look at the “employee” JSON file at the beginning of the article. The following code block reads this file and saves it into a Python dictionary.
>>> with open("employee.json", "r") as read_file: . employee = json.load(read_file) . >>> print(employee) , ]>
Now employee is a Python dictionary object.
It is important to emphasize the difference between the json library’s load( ) and loads() methods. The load method is used for creating a Python object from a JSON file, whereas the loads() method converts a JSON string to a Python object.
From Python Object to JSON String: Serializing
Just like we can create a Python object from a JSON file, we can convert a Python object to a JSON string or file. This process is called serialization.
The dumps() method converts a Python dictionary to a JSON string. In the deserializing section, we created a dictionary called myobject . It can be converted back to a JSON string as follows:
The output is a string (notice the single quotes around the curly brackets), so we cannot access a specific key-value pair as we do with dictionaries.
This very simple string is not difficult to read. However, JSON strings can be much longer and have nested parts. For such cases, the dumps() method provides a more readable way of printing. We can pretty print this string by setting the optional indent parameter:
>>> print(json.dumps(myobject, indent=3))
The dumps() method also has a parameter for sorting by key:
>>> print(json.dumps(myobject, indent=3, sort_keys=True))
JSON files are often used for serialization (pickling), e.g. for when you want to maintain some data between the runs of your application. You can learn more about object serialization in this article.
Creating a JSON File with dump()
The dumps() method converts a Python object to a JSON formatted string. We can also create a JSON file from data stored in a Python dictionary. The method for performing this task is dump() .
Let’s use the dump() method for creating a JSON file. We’ll use the employee dictionary we created in the previous section:
with open("new_employee.json", "w") as write_file: json.dump(employee, write_file, indent=4)
This creates a file called new_employee.json in your current working directory and opens it in write mode. Then, we use the dump() method to serialize a Python dictionary.
The dump() method takes two positional arguments. The first one is the object that stores the data to be serialized (here, a Python dictionary). The second one is the file to write the serialized data. The indent parameter is optional.
Printing in the Command Line
The tool() method of the json library allows for pretty-printing JSON files in the command line. Let’s try it on the new_employee.json file we created in the previous section.
The first step is to open a command-line interface. Then we need to change the directory to the location where the new_employee.json file is saved.
The following command will print the JSON file in a nice, clean format:
python -m json.tool new_employee.json
The following image shows how it looks in the Windows command prompt.
Learn More About JSON and Python
We have covered how to read and write JSON files in Python. The built-in json library makes it easy to do both of these. One of the advantages of Python is the rich selection of built-in and third-party libraries that simplify most tasks.
If you are learning or plan to learn Python, our Learn Programming with Python track is a great way to start. It is designed for beginners and contains 5 interactive courses. The advantage of learning with an interactive course is that you get real, hands-on practice writing code; this is essential for learning a programming language.
LearnPython.com also offers an entire course dedicated to JSON Files in Python. The course is also interactive and contains 35 exercises. If you want to practice the concepts we’ve discussed in this article, this course is for you. Happy learning!
Python JSON – How to Convert a String to JSON
Dionysia Lemonaki
In this tutorial you’ll learn the basics of JSON – what it is, where it is most commonly used, and its syntax.
You’ll also see how to convert a string to JSON in Python.
What is JSON?
JSON stands for JavaScript Object Notation.
It is a data format that’s used for storing and transferring information for web applications.
JSON was inspired by the JavaScript programming language, but it’s not tied to only one language.
Most modern programming languages have libraries for parsing and generating JSON data.
Where is JSON used?
JSON is mostly used for sending and receiving data between a server and a client, where the client is a webpage or web application.
It’s a much more solid format to use during the request-response cycle web applications use when connecting over a network. This is compared to the complicated and less compact XML, which was the format of choice years ago.
Basic JSON syntax
In JSON, data is written in key-value pairs, like so:
Data is enclosed in double quotation marks and the key-value pair is separated by a colon.
There can be more than one key-value pair and each one is separated by a comma:
"first_name": "Katie", "last_name": "Rodgers"
The example above showed an object, a collection of multiple key-value pairs.
Objects are inside curly braces:
You can also create arrays, an ordered list of values, with JSON. In that case, arrays are contained inside square brackets:
[ < "first_name": "Katie", "last_name": "Rodgers" >, < "first_name": "Naomi", "last_name": "Green" >, ] // or: < "employee": [ < "first_name": "Katie", "last_name": "Rodgers" >, < "first_name": "Naomi", "last_name": "Green" >, ] > //this created an 'employee' object that has 2 records. // It defines the first name and last name of an employee
How to work with JSON data in Python
Include the JSON module for Python
To use JSON with Python, you’ll first need to include the JSON module at the top of your Python file. This comes built-in to Python and is part of the standard library.
So, say you have a file named demo.py . At the top you would add the following line:
Use the json.loads() function
If you have JSON string data in your program like so:
#include json library import json #json string data employee_string = '' #check data type with type() method print(type(employee_string)) #output #
you can turn it into JSON in Python using the json.loads() function.
The json.loads() function accepts as input a valid string and converts it to a Python dictionary.
This process is called deserialization – the act of converting a string to an object.
#include json library import json #json string data employee_string = '' #check data type with type() method print(type(employee_string)) #convert string to object json_object = json.loads(employee_string) #check new data type print(type(json_object)) #output #
You can then access each individual item, like you would when using a Python dictionary:
#include json library import json #json string data employee_string = '' #check data type with type() method print(type(employee_string)) #convert string to object json_object = json.loads(employee_string) #check new data type print(type(json_object)) #output # #access first_name in dictionary print(json_object["first_name"]) #output #Michael
Let’s take another example:
import json #json string employees_string = ''' < "employees": [ < "first_name": "Michael", "last_name": "Rodgers", "department": "Marketing" >, < "first_name": "Michelle", "last_name": "Williams", "department": "Engineering" >] > ''' #check data type using the type() method print(type(employees_string)) #output #
import json emoloyees_string = ''' < "employees" : [ < "first_name": "Michael", "last_name": "Rodgers", "department": "Marketing" >, < "first_name": "Michelle", "last_name": "Williams", "department": "Engineering" >] > ''' data = json.loads(employees_string) print(type(data)) #output #
import json employees_string = ''' < "employees" : [ < "first_name": "Michael", "last_name": "Rodgers", "department": "Marketing" >, < "first_name": "Michelle", "last_name": "Williams", "department": "Engineering" >] > ''' data = json.loads(employees_string) print(type(data)) #output # #access first_name for employee in data["employees"]: print(employee["first_name"]) #output #Michael #Michelle
Conclusion
And there you have it – you now know the basics of using JSON in Python.
If you want to learn more about Python, freeCodeCamp has a Python Certification which takes you from the fundamentals such as variables, loops, and functions to more advanced concepts such as data structures. In the end you’ll also build 5 projects.
Thanks for reading and happy learning!
Python Convert From Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Example
Convert from Python to JSON:
# a Python object (dict):
x = «name»: «John»,
«age»: 30,
«city»: «New York»
>
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
You can convert Python objects of the following types, into JSON strings:
Example
Convert Python objects into JSON strings, and print the values:
print(json.dumps())
print(json.dumps([«apple», «bananas»]))
print(json.dumps((«apple», «bananas»)))
print(json.dumps(«hello»))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Example
Convert a Python object containing all the legal data types:
Python JSON
JSON is text, written with JavaScript object notation.
JSON in Python
Python has a built-in package called json , which can be used to work with JSON data.
Example
Parse JSON — Convert from JSON to Python
If you have a JSON string, you can parse it by using the json.loads() method.
Example
Convert from JSON to Python:
# the result is a Python dictionary:
print(y[«age»])
Convert from Python to JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Example
Convert from Python to JSON:
# a Python object (dict):
x = «name»: «John»,
«age»: 30,
«city»: «New York»
>
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
You can convert Python objects of the following types, into JSON strings:
Example
Convert Python objects into JSON strings, and print the values:
print(json.dumps())
print(json.dumps([«apple», «bananas»]))
print(json.dumps((«apple», «bananas»)))
print(json.dumps(«hello»))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Example
Convert a Python object containing all the legal data types:
Format the Result
The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
The json.dumps() method has parameters to make it easier to read the result:
Example
Use the indent parameter to define the numbers of indents:
You can also define the separators, default value is («, «, «: «), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:
Example
Use the separators parameter to change the default separator:
Order the Result
The json.dumps() method has parameters to order the keys in the result:
Example
Use the sort_keys parameter to specify if the result should be sorted or not: