Python tuple to json

How can I represent python tuple in JSON format?

In this article, we will show you how to represent a tuple in python in JSON format. We will see the below-mentioned methods in this article:

  • Converting Python Tuple to JSON
  • Converting Python Tuple with Different Datatypes to JSON String
  • Parsing JSON string and accessing elements using json.loads() method.
  • Convert the dictionary of tuples to JSON using json.dumps()

What is JSON?

JSON (JavaScript Object Notation) is a simple lightweight data-interchange format that humans can read and write. Computers can also easily parse and generate it. JSON is a computer language that is based on JavaScript. It is a language-independent text format that may be used with Python, Perl, and other programming languages. Its primary function is to transfer data between a server and web applications.

JSON is composed of two structures:

  • A collection of name/value pairs. This is accomplished by the use of an object, record, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. This is accomplished by the use of an array, vector, list, or sequence.

JSON in Python

In Python, there are a few packages that support JSON, such as metamagic. json, jyson, simplejson, Yajl-Py, ultrajson, and JSON are all supported.

An example of JSON data is shown below. The data representation looks very similar to Python dictionaries.

Python’s JSON library is used for data serialization. JSON is an abbreviation for Javascript object notation.

Encoding is the process of converting a Python object to JSON. Python’s json module can be used to work with JSON objects. However, before you can use the module, you must first import it.

The encoding is carried out using the JSON library method json.dumps(). By default, Python’s JSON Library provides the following conversion of Python objects into JSON objects.

Python JSON
dict Object
tuple Array
list Array
Unicode String
number – int, long number – int
float number – real
True True
False False
None Null

Converting Python Tuple to JSON

Use the json.dumps() function to convert a Python tuple to JSON. To convert an object into a json string, the json.dumps() method accepts a tuple as a parameter.

Import the json module at the top of the Python code to deal with json-related functions.

Syntax

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task –.

  • Use the import keyword to import the json module
  • Create a variable to store the input tuple.
  • Use the json.dumps() function(converts a Python tuple to JSON) for converting input tuple into JSON string by passing the input tuple as an argument to it.
  • Print the resultant JSON string object.
  • Print the type of the resultant JSON string object using type() function(returns the data type of an object)
Читайте также:  Set tracking in html

Example

The following program converts the input tuple into JSON using json.dumps() function in python –

# importing json module import json # input tuple inputTuple = ("hello", "tutorialspoint", "python") # converting input tuple into json string jsonObject = json.dumps(inputTuple) # printing the resultant JSON string print(jsonObject) print(type(jsonObject))

Output

On executing, the above program will generate the following output −

[«hello», «tutorialspoint», «python»]

Converting Python Tuple with Different Datatypes(Heterogeneous datatypes) to JSON String

If you have a Python tuple containing many data types, you may use the json.dumps() method to convert it to a JSON string.

Example

The following program converts the input tuple containing datatypes like String, Integer, Boolean, and Float into a JSON string –

# importing json module import json # input tuple containing several datatypes(Heterogenous data types) inputTuple = (5, 9.5, "tutorialspoint", False) # converting input tuple into json string jsonObject = json.dumps(inputTuple) # printing the resultant JSON string print(jsonObject) # printing the type of resultant JSON string print(type(jsonObject))

Output

On executing, the above program will generate the following output −

[5, 9.5, «tutorialspoint», false]

Parsing JSON string and accessing elements using json.loads() method.

If you have a Python tuple containing many data types, you may use the json.dumps() method to convert it to a JSON string.

Example

The following program parse JSON string and accesses elements using json.loads() method –

# importing json module import json # input tuple containing sevaral datatypes inputTuple = (5, 9.5, "tutorialspoint", False) # converting input tuple into json string jsonObject = json.dumps(inputTuple) # printing the resultant JSON string print(jsonObject) # printing the type of resultant JSON string print(type(jsonObject)) print("Converting JSON string object into list:") # converting JSON string object into list using json.loads() function jsonArray= json.loads(jsonObject) # accessing the first element of JSON array print("First element of JSON array:", jsonArray[0]) # printing the type of json array print("Type of json array:", type(jsonArray))

Output

On executing, the above program will generate the following output −

[5, 9.5, «tutorialspoint», false] Converting JSON string object into list: First element of JSON array: 5 Type of json array:

Convert dictionary of tuples to JSON using json.dumps()

The json.dumps() converts dictionary of tuples to json

Syntax

json.dumps(dictionary, indent)

Parameters

Example

The following program converts the input dictionary of tuples into JSON using json.dumps() −

# importing json module import json # input dictionary dict = "id": ("1", "2", "3"), "languages": ("python", "java", "c++"), "authors": ("abc", "xyz", "pqr") > # converting dictionary of tuples into json result = json.dumps(dict, indent=2) # printing the resultant json print(result)

Output

On executing, the above program will generate the following output −

Conclusion

We learned how to represent a tuple in JSON object/string in this article. With an example, we learned a brief overview of the JSON object. We also learned how to convert a tuple dictionary to JSON.

Источник

Python tuple to json

Last updated: Feb 19, 2023
Reading time · 3 min

banner

# Convert a Tuple to JSON in Python

Use the json.dumps() method to convert a tuple to JSON.

The json.dumps() method will convert the Python tuple to a JSON array and will return the result.

Copied!
import json my_tuple = ('bobby', 'hadz', 'com') json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["bobby", "hadz", "com"]' print(type(json_str)) # 👉️

We used the json.dumps method to convert a tuple to a JSON string.

The json.dumps method converts a Python object to a JSON formatted string.

# Python tuples are JSON serializable

Python tuples are JSON serializable, just like lists or dictionaries.

The JSONEncoder class supports the following objects and types by default.

Python JSON
dict object
list, tuple array
str string
int, float, int and float derived Enums number
True true
False false
None null

The process of converting a tuple (or any other native Python object) to a JSON string is called serialization.

Whereas, the process of converting a JSON string to a native Python object is called deserialization.

# Parsing the JSON string returns a Python list

When you parse the JSON string into a native Python object, you get a list back.

Copied!
import json my_tuple = ('bobby', 'hadz', 'com') # ✅ convert tuple to JSON json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["bobby", "hadz", "com"]' print(type(json_str)) # 👉️ # -------------------------------- # ✅ parse JSON string to native Python object parsed = json.loads(json_str) print(parsed) # 👉️ ['bobby', 'hadz', 'com'] print(type(parsed)) # 👉️ print(parsed[0]) # 👉️ bobby print(parsed[1]) # 👉️ hadz

The json.loads method parses a JSON string into a native Python object.

Notice that we got a list object after parsing the JSON string.

This is because both list and tuple objects get converted to a JSON array when serialized.

You can use the tuple() class to convert the list to a tuple after parsing the JSON string.

Copied!
import json my_tuple = ('bobby', 'hadz', 'com') json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["bobby", "hadz", "com"]' print(type(json_str)) # 👉️ # -------------------------------- # 👇️ convert to tuple parsed = tuple(json.loads(json_str)) print(parsed) # 👉️ ('bobby', 'hadz', 'com') print(type(parsed)) # 👉️ print(parsed[0]) # 👉️ bobby print(parsed[1]) # 👉️ hadz

The example uses the tuple() class to convert the list we got after parsing the JSON string.

You can use bracket notation to access the tuple at a specific index after parsing the JSON.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

# Converting a mixed tuple to JSON

You can also use the json.dumps method to convert a tuple containing elements of multiple types to JSON.

Copied!
import json my_tuple = ('bobby', 1, 'hadz', 2, 'com') json_str = json.dumps(my_tuple) print(json_str) # 👉️ '["bobby", 1, "hadz", 2, "com"]' print(type(json_str)) # 👉️

However, you have to make sure that your tuple contains one of the supported types.

The JSONEncoder class supports the following objects and types by default.

Python JSON
dict object
list, tuple array
str string
int, float, int and float derived Enums number
True true
False false
None null

If your tuple stores values of a type that is not contained in the column on the left, the default JSONEncoder won’t be able to convert the tuple to JSON.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

How to Convert Python Tuple to JSON Array?

To convert Python Tuple to JSON Array, use json.dumps() method with the tuple passed as argument to the method.

In this tutorial, we shall learn how to create a JSON object from a tuple, with the help of example Python programs.

Syntax of json.dumps()

Following is the syntax of json.dumps() function.

jsonStr = json.dumps(mytuple)

Examples

1. Convert a tuple of strings to JSON string

In the following example, we have created a tuple and converted it to a JSON String. Python Tuple object converts to Array in JSON.

Python Program

import json #python tuple mytuple = ("python", "json", "mysql") #convert to JSON string jsonStr = json.dumps(mytuple) #print json string print(jsonStr)

2. Convert a tuple with different datatypes to JSON string

In the following example, we have created a tuple with values of different datatypes and converted it to a JSON String. Also, we will try to parse this JSON and access the elements.

Python Program

import json #python tuple mytuple = ("python", "json", 22, 23.04) #convert to JSON string jsonStr = json.dumps(mytuple) #print json string print(jsonStr) #parse json jsonArr = json.loads(jsonStr) #print third item of the json array print(jsonArr[2])

Summary

In this Python JSON Tutorial, we learned how to convert a Python Tuple to a JSON String.

Источник

How to Convert Python Tuple to JSON

To convert a tuple to JSON in Python, you can use the “json.dumps()” method. The json.dumps() method accepts the tuple to convert an object into a json string.

Example

import json tup = ("Dhirubhai", "Ratan", "Timothee") jsonObj = json.dumps(tup) print(jsonObj)

We got the json string in the output.

The JSON library in Python is used for data serialization. JSON stands for Javascript object notation. The operation of converting Python Object to JSON is called Encoding.

To work with JSON objects, you can use Python’s json module. However, you need to import the module before you can use it.

The encoding is done with the help of the JSON library method json.dumps(). Python’s JSON Library delivers the following conversion of Python objects into JSON objects by default.

Python JSON
dict Object
tuple Array
list Array
Unicode String
number – int, long number – int
float number – real
True True
False False
None Null

Converting Tuple with Different Datatypes to JSON String

If you have a Python tuple with different data types, you can convert it into a JSON string using the json.dumps() method.

import json tup = ("Dhirubhai", 72, True, 5.8) jsonObj = json.dumps(tup) print(jsonObj) print(type(jsonObj))

In this example, we have created a tuple with values of different data types like String, Integer, Boolean, and Float and converted it to a JSON String.

We can parse this JSON and access the elements using json.loads() method.

import json tup = ("Dhirubhai", 72, True, 5.8) jsonObj = json.dumps(tup) print(jsonObj) print(type(jsonObj)) print("Converting JSON to List") jsonArr = json.loads(jsonObj) print(jsonArr[1]) print(type(jsonArr))
["Dhirubhai", 72, true, 5.8] Converting JSON to List 72 

The json module makes it easy to parse JSON strings and files containing JSON objects. The json.loads() method converts the JSON string into a list.

Источник

Оцените статью