How To Convert JSON To Tuple In Python

JSON is JavaScript Object Notation. It is used for storing and exchanging data between browser & server and that can only be in the text. It is a language-independent data format.

So let’s see here how can we convert JSON data to a tuple in Python.

Convert JSON To Tuple In Python

Python has a built-in library called JSON which is used to work with JSON data. But first, before using it in your program you need to import it. You can do this by using

import json

This json library has many useful methods to work on JSON files. But data has to be parsed.

 

Now, for example, this data is stored in JSON.

{ 
"name":"Josh", "age":56, "city":"LA", “phone”:”8945653214”
}
//This data is saved as json_file.json

Now we want to convert this to a tuple in Python. But before converting it to a tuple, we converted this in dict in Python. This can be achieved by using json.loads method. And then you can easily get the values from a dict like a normal dictionary.

import json
f_data = open(“json_file.json”)
json_data = json.loads(f_data)
f_data.close()
print(json_data)

Now json_data has json file data in dictionary format.

If you see the output of this file.

How To Convert JSON To Tuple In Python

 

Now the data is in dict form now we get data by converting dict to a tuple.

This can be done by using tuple() method in the Python standard library.

Just by doing the above same steps and using tuple() method and printing data.

import json
f_data = open(“json_file.json”)
json_data = json.loads(f_data)
f_data.close()
print(tuple(json_data.items()))

json to tuple

 

So using this method you can convert JSON data into tuple in Python.

Here you can see in the output that it is a nested tuple. The first element in each tuple is key of the dictionary and in the second it is the respective value of that key and you can see this in every program.

Leave a Reply

Your email address will not be published. Required fields are marked *