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.

{
   "tutorialspoint": [
      {
         "article":"1",
         "category": "python",
         "writtenby": "abc"
      },
      {
         "article":"2",
         "category": "Java",
         "writtenby": "xyz"

      }
   ],
   "address":[
      {
         "place": "hitechcity",
         "websitelink":"www.tutorialspoint.com"
      }
   ]
}

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

jsonStr = json.dumps(tuple)

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)

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"]
<class 'str'>

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]
<class 'str'>

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]
<class 'str'>
Converting JSON string object into list:
First element of JSON array: 5
Type of json array: <class 'list'>

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

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

Syntax

json.dumps(dictionary, indent)

Parameters

  • dictionary - input dictionary

  • indent - no. of units of indentataion

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 −

{
   "id": [
      "1",
      "2",
      "3"
   ],
   "languages": [
      "python",
      "java",
      "c++"
   ],
   "authors": [
      "abc",
      "xyz",
      "pqr"
   ]
}

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.

Updated on: 28-Oct-2022

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements