Python dictionary list to json

How to Convert List to JSON in Python

To convert a list to JSON in Python, you can use the “json.dumps()” function. This function takes a list as an argument and returns a JSON string. For example, if you have a list called main_list = [1, 2, 3], json.dumps() returns json string [1, 2, 3].

Syntax

import json json.dumps(list) 

Example

import json data = ["DisneyPlus", "Netflix", "Peacock"] json_string = json.dumps(data) print(json_string)
["DisneyPlus", "Netflix", "Peacock"]

You can see that we converted json string to a list using the dumps() method.

How to Convert a List of Dictionaries to JSON

You can use the json.dumps() method to convert a list of dictionaries to JSON. This function preserves the original data and structure of the list of dictionaries.

import json list_of_dicts = [, ] json_str = json.dumps(list_of_dicts) print(json_str)

You can see that we converted a list of dictionaries to json string without losing any original data.

How to Convert a List of Lists to JSON

You can use the json.dumps() method to convert a list of lists to json string in Python. It accepts the list of lists as an argument and returns the json string without losing input data.

import json list_of_lists = [[19, 21], [11, 18], [46]] json_str = json.dumps(list_of_lists) print(json_str)

How to Write JSON data to a file in Python

To write a json data into a file, use the with open() function in the “w” mode and then use the json.dump() method to write all the content in the file.

Let’s implement a program to write the JSON data into a file.

import json data =  "Mike": "Finn", "Will": "Noah"> with open('app.json', 'w') as f: json.dump(data, f)

In your app.json file, you have the data json written.

If we want to get the utf8-encoded, then write the following code.

import json data =  "Mike": "Finn", "Will": "Noah"> with open('app.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)

The following indented output will be written in the file.

  "Eleven": "Millie", "Mike": "Finn", "Will": "Noah" >

Источник

Convert Python Dictionary to JSON

How to convert a dictionary to JSON in Python? We can use the json.dump() method and json.dumps() method to convert a dictionary to a JSON string.

JSON stands for JavaScript Object Notation and is used to store and transfer data in the form of text. It represents structured data. You can use it, especially for sharing data between servers and web applications. Python has a built-in package called json to work with JSON file or strings. The data in the JSON is made up of the form of key/value pairs and they can be enclosed with <> . Look wise it is similar to a Python dictionary. But JSON keys must be sting-type objects with a double-quoted and values can be any datatype such as string, integer, nested JSON, a list, a tuple, or even another dictionary.

A Python dictionary is a collection that is unordered, mutable and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

 # Create dictionary courses = < "course": "python", "fee": 4000, "duration": "30 days">print(courses) 

1. Quick Examples of Converting Dictionary to JSON

Following are quick examples of converting a dictionary to JSON.

 # Below are the quick examples. # Example 1: Convert dictionary to JSON object json_obj = json.dumps(courses, indent = 4) # Example 2: Convert nested dictionary to JSON json_obj = json.dumps(courses, indent = 4) # Example 3: Convert dictionary to JSON array array = [ for x in courses] json_obj = json.dumps(array) # Example 4: Convert dictionary to JSON object using sort_keys json_obj = json.dumps(courses, indent = 4, sort_keys = True) 

2. Convert Dictionary to JSON in Python

You can convert a Python dictionary (dict) to JSON using the json.dump() method and json.dumps() method from json module, these functions also take a dictionary as an argument to convert it to JSON.

2.1 Syntax of json.dump() Method

Following is the syntax of json.dump() method.

 # Syntax of json.dump() function json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) 

2.1.1 Parameters

This function allows the following parameters.

  • dictionary: Name of a dictionary that should be converted to JSON object.
  • indent: Specifies the number of units we have to take for indentation.

2.1.2 Return Value

It returns a JSON string object.

2.1.3 Using json.dump() to Write JSON Data to a File in Python

Let’s see an example of writing a Python object to a JSON file. The data parameter represents the JSON data to be written to the file. This can be any Python object that is JSON serializable, such as a dictionary or a list. Alternatively, you can also put this data to a file and read json from a file into a object.

Following is the syntax of writing JSON data to file.

 # Syntax of write JSON data to file import json with open("data.json", "w") as outfile: # json_data refers to the above JSON json.dump(json_data, outfile) 
  • json_data is the Python object to be encoded as JSON.
  • «data.json» is the name of the file where the JSON data will be written.
  • «w» specifies that the file will be opened in write mode.
  • outfile is the file-like object where the JSON data will be written.

Here, in the below example json_data is a dictionary object which I will write to a file.

 # Import json module import json # Create dictionary object which is json representation json_data = < "name": "Python", "year": 1991, "creator": "Guido van Rossum", "popular": True ># Writing JSON data to a file using a file object with open("data.json", "w") as outfile: # json_data refers to the above JSON json.dump(json_data, outfile) 

As you can see from the above, the JSON file has been returned from JSON data. When we want to see the JSON data on the console you can use json.dumps() function. It will return the JSON data from the Python object.

2.2 Syntax of json.dumps()

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

 # Syntax of json.dumps() function json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) 

2.2.1 Parameters

This function allows the following parameters.

  • dictionary: Name of a dictionary that should be converted to JSON object.
  • indent: Specifies the number of units we have to take for indentation.

2.2.2 Return Value

3. Usage of dumps() to Convert Dictionary to JSON

json.dumps() function is json module of Python that is used to convert Python object(here, dictionary) to JSON object. This function is also used to convert data types such as a dictionary, list, string, integer, float, boolean, and None into JSON.

Note: Before going to use json.dumps() we have to import json module.

 # Type of courses print(type(courses)) # Convert dictionary to JSON object import json json_obj = json.dumps(courses, indent = 4) print(json_obj) print(type(json_obj)) 

Python convert dictionary JSON

4. Convert Python Nested Dictionary to JSON

Let’s use another example with a nested dictionary and convert to JSON using json.dumps() function. A dictionary inside another dictionary is called a nested dictionary. To convert the nested dictionary into a JSON object, we have to pass the given dictionary and indent param into dumps() function. It will convert the nested dictionary into a JSON object with specified indentation.

 # Create nested dictionary import json courses = < "Python": , "Java": , > print(courses) # Convert nested dictionary to json json_obj = json.dumps(courses, indent = 4) print(json_obj) print(type(json_obj)) 

Python convert nested dictionary JSON

5. Convert Dictionary to JSON Array

Let’s create an array of dictionaries using dictionary comprehension and then convert the array to a JSON array. For example,

 # Convert dictionary to JSON array array = [ for x in courses] print(json.dumps(array)) print(type(json.dumps(array))) # Output: # [, , ]

6. Convert Dictionary to JSON Quotes

First, we can create a class using the __str__(self) method which is used for string representation to convert a dictionary into a JSON object. Then we create a variable with single quoted values and declare it as a dictionary using str(self) method. Finally, using the dumps() function we can convert the dictionary to JSON quotes(which means double quoted). For example,

 # Convert dictionary to JSON quotes # Create a class using the __str__(self) method import json class courses(dict): def __str__(self): return json.dumps(self) # Using the json.dumps() function # To convert dictionary to JSON quotes list = [['Python', 'Pandas']] print("The dictionary: \n", list) json_obj = courses(list) print("The json object:", json_obj) # Output: # The dictionary: # [['Python', 'Pandas']] # The json object:

7. Convert Sorted Dictionary to JSON using sort_keys

Set sort_keys() param as True and then pass it into the dumps() method along with given dictionary and indent param, it will sort the dictionary and convert it into a JSON object.

 # Convert dictionary to JSON object using sort_keys json_obj = json.dumps(courses, indent = 4, sort_keys = True) print(json_obj) # Output: #

8. Conclusion

In the article, I have explained json.dumps() function and using its parameters how we can convert the dictionary to JSON in python with examples.

  • Remove multiple keys from Python dictionary
  • Python get dictionary keys as a list
  • Get all keys from dictionary in Python
  • Python sort dictionary by key
  • How to sort dictionary by value in Python
  • How to create nested dictionary in Python
  • Python check if key exists in dictionary
  • Python iterate over a dictionary
  • Python add keys to dictionary
  • How to append Python dictionary to dictionary?
  • Python json.loads() Method with Examples
  • Python Read JSON File
  • How to Pretty Print a JSON file in Python?
  • Convert Python List to JSON Examples
  • Convert JSON Object to String in Python
  • Python Write JSON Data to a File?
  • How to add items to a Python dictionary?
  • Sort Python dictionary explained with examples
  • Python dictionary comprehension
  • Dictionary methods
  • Python get dictionary values as list

References

You may also like reading:

Источник

Читайте также:  Php объем использованной памяти
Оцените статью