![]() |
JSON (JavaScript Object Notation) is a widely used data interchange format, and Python provides excellent support for working with JSON data. However, when it comes to converting generator objects to JSON, there are several methods to consider. In this article, we’ll explore some commonly used methods. Convert Generator Object To JSON In PythonBelow, are the ways To Convert Generator objects to JSON In Python.
Convert Generator Object To JSON Using json.dumps() MethodIn this example, the below code involves the creation of a generator object using a generator expression, followed by its conversion to a list. The list is then serialized to a JSON-formatted string using `json.dumps()`. The resulting JSON data is printed, along with its data type, illustrating the transformation of the generator data into a JSON string. Python3
Output
<class 'generator'> [0, 1, 2, 3, 4] <class 'str'> Convert Generator Object To JSON Using the
|
import json def generator_to_list(generator_obj): result_list = [] for item in generator_obj: result_list.append(item) yield item generator_obj = (x for x in range ( 5 )) print ( type (generator_obj)) # Method 5: Using yield result_generator = generator_to_list(generator_obj) json_data = json.dumps( list (result_generator)) print (json_data) print ( type (json_data)) |
<class 'generator'> [0, 1, 2, 3, 4] <class 'str'>
In this example, below code create a generator object using a generator expression, then converts it to a dictionary format with the key “data” and a list of values. This dictionary is subsequently serialized into a JSON-formatted string using `json.dumps()`. The resulting JSON data is printed along with its data type.
import json generator_obj = (x for x in range ( 5 )) print ( type (generator_obj)) # Convert to Dictionary result_dict = { "data" : list (generator_obj)} json_data = json.dumps(result_dict) print (json_data) print ( type (json_data)) |
<class 'generator'> {"data": [0, 1, 2, 3, 4]} <class 'str'>
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |