Loading...

How To Convert A Dictionary To JSON in Python?

How To Convert A Dictionary To JSON in Python?

Python is a high-level interpreted programming language released in 1991 that is used to build server-side applications like web apps using Django frameworks and is also used for big data analysis and machine learning. JSON stands for JavaScript Object Notation, and in this article, we will discuss everything about it, including conversion from dictionary to JSON and vice versa. Also learn indentation, sorting keys, and separators while converting from dictionary to JSON format.

JSON data is a data format used by many servers. It’s a format that looks a lot like Python dictionaries. Once the data is saved as a JSON string, you can send it to any server, and that language will receive it and convert it back to an object type of that native language. That’s why we use it because it’s very easy to use, portable, and friendly across multiple servers and many machines. So JSON data is replaced by pretty much the same XML used before, but it’s very slow to parse and generate the data. It is used for configuration files, strong data, and APIs, which we receive in JSON format.

Python dictionary is a key-value pair that uses curly braces, and inside the braces, we have the key followed by a colon again followed by a value. If the key is not a number, then we wrap it with double quotes or with a single quote. A dictionary doesn’t care about the order; unlike lists, it maps certain data to a certain key.

While in JSON, we use curly braces, and data must be a string when used as an object, we will wrap the whole thing with a single quote. The only rule in these is that we must wrap all of the keys in double quotes at the end; a comma will result in invalid JSON data. We can’t access it like a dictionary because it’s a string, so you need to convert it to something that Python will understand, and that’s done by using the JSON library, so we have to import the JSON library.

Converting JSON to Dict?

import json jdata='{"name":"Alex","age":21}' data=json.loads(jdata) print(data) print(jdata) print(type(data)) print(type(jdata))
Code language: Python (python)
{'name': 'Alex', 'age': 21} {"name":"Alex","age":21} <class 'dict'> <class 'str'>
Code language: Bash (bash)

Now when want to access we can simply do it by,

print(data['name']) #output gonna be: Alex
Code language: Python (python)

If I want to access and use JData in Python, we have to convert it to a dictionary that Python recognizes.

type(jdata) #str type(data) #dict
Code language: Python (python)

This is a single object; if we want to add another person’s name and age here, we can use triple quotes with multi-line syntax. 

import json jdata='''[{"name":"Alex","age":21}, {"name":"Mob","age":24}, {"name":"John","age":21,"Subjects":["Maths","science"], "skills":{ "HTML":"good", "javascript":"bad" } }]''' data=json.loads(jdata) print(data[1]["name"]) print(data[2]["skills"]["HTML"]) print(jdata) print(data)
Code language: Python (python)

Output:

Mob good [{"name":"Alex","age":21}, {"name":"Mob","age":24}, {"name":"John","age":21,"Subjects":["Maths","science"], "skills":{ "HTML":"good", "javascript":"bad" } }] [{'name': 'Alex', 'age': 21}, {'name': 'Mob', 'age': 24}, {'name': 'John', 'age': 21, 'Subjects': ['Maths', 'science'], 'skills': {'HTML': 'good', 'javascript': 'bad'}}]
Code language: Bash (bash)

Now we will put these in a file with a .json file example like first.json in that file will be a string, just plain text. When we read it into our program, it’s going to read as a string.

import json infile=open("first.json",'r')
Code language: Python (python)

Now we are reading as a string we want into JSON format so

import json infile=open("first.json",'r') jdata=infile.read() data=json.loads(jdata)
Code language: Python (python)

So this is how JSON data works in Python. Now if we want to pass Python data back to another server in order to transfer data to other servers, we cannot transfer data as an object; it needs to be serialized back into a string, so we need to reverse the process here, which we will do in further detail in this blog.

Dictionary to Json ( Formatting)

With json.dumps, the Python dictionary will be converted to a JSON string.

import json data={"name":"Alex","age":21} jdata=json.dumps(data) print(type(jdata)) print(type(data))
Code language: Python (python)
<class 'str'> <class 'dict'>
Code language: Bash (bash)

 Indent

We can also add an indentation for readable JSON format, so we add it as an extra argument in the json.dump function.

#we will consider above data jdata=json.dumps(data,indent=4) print(jdata)
Code language: Python (python)

Sort_keys

jdata = json.dumps(data,sort_keys=True) print(jdata)
Code language: Python (python)

By setting sort_keys=True, it alphabetically sorts the keys in a JSON object. You must use True, not true it throws an error in python.

{"age":21,"name":"Alex"}
Code language: Bash (bash)

Separators

By default, separators make use of a semicolon between keys and values and a comma between the items, unless we set it in a different way. Let’s see an example.

jdata = json.dumps(data, separators=(';', '='))
Code language: Python (python)
{"name"="Alex";"age"=21}
Code language: Bash (bash)

We can experiment with a different way of using characters, making it more readable.

jdata = json.dumps(data, separators=(' ', ':'))
Code language: Python (python)
{"name":"Alex" "age":21}
Code language: Bash (bash)

How do I convert a dictionary into a JSON file?

with open("second.json",'w') as fi: json.dump(data,fi)
Code language: Python (python)

When we run, then second.json file is going to pop up, and then we open the file and see JSON format. If you want to format JSON nicely, you can use indentation or simply install the extension called Prettify JSON.

Conclusions

A dictionary is a built-in Python data structure that is very similar to JSON objects; thus, we use a python dictionary to represent. So to convert from the Python dictionary to JSON, we use the json.dump method, which comes with additional formats as an argument for indentation, sorting keys, and separator choices. And converting from JSON to the Python dictionary is done by using the json.loads method.

Frequently Asked Questions to Resolve (FAQs)

Is Python a dictionary like JSON?

A dictionary is an in-built data structure in Python that is very similar to JSON objects; that’s why we use a python dictionary to represent it. But the main purpose is that once data is saved as a JSON string, you can send it to any server, and that language will receive it and convert it back to an object type of that native language. It is used for configuration files, strong data, and APIs, which we receive in JSON format. A dictionary, on the other hand, is used to perform manipulations and tasks with Python programs. 

How to convert a Python dictionary into JSON?

To convert the Python dictionary into JSON, we use the json.dump() functions, which take input as a dictionary and return it as a JSON object.

Which method is used to convert a dictionary to a JSON string?

json.dumps() is used to convert a dictionary to a JSON string.

How is a dictionary represented in JSON?

In JSON, the dictionary is represented as an object that has a key-value pair; it can be anything such as a string, int, boolean, or even a JSON object that uses curly braces, and inside the braces, we have the key followed by a colon again followed by a value.

How do you convert a dictionary into a JSON string?

With the json.dumps function, the Python dictionary will be converted to a JSON string. For example, if data is a dictionary, we would use ‘json.dumps(data)’ which would return the JSON object.

Sharing is caring

Did you like what Nithin Reddy wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far