Python list dict to json

Convert Python List to JSON Examples

How to convert a list to JSON in python? You can use the json.dumps() method to convert a Python list to a JSON string. This function takes a list as an argument and returns the JSON value. The json.dumps() function converts data types such as a dictionary, string, integer, float, boolean, and None into JSON. In this article, I will explain the syntax of how to convert a list to JSON in Python, its parameters, and explain how to use it.

1. Quick Examples of Convert List to JSON

If you are in a hurry, below are some quick examples of how to convert list to JSON.

 # Below are the quick examples # Example 1: Convert python list to JSON numbers = [25, 36, 48, 54] json_numbers = json.dumps(numbers) # Example 2: Convert python string type list to JSON technology = ["Hadoop", "Spark", "Python"] json_string = json.dumps(technology) # Example 3: Convert list of dictionaries to JSON my_dict = [, ] jsondict = json.dumps(my_dict) # Example 4: Convert a list of lists to JSON List = [[], []] jsonList = json.dumps(List) 

2. Syntax of json.dumps() Function

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

 # Syntax of json.dumps() function import json json.dumps(list) 

You have to import json package to use json.dumps() function.

Читайте также:  Плавный скролл html css

3. Convert List to JSON

You can use the json module to convert a list to a JSON object. The json.dumps() function converts a Python object, in this case, a list, into a JSON string. You can see that below examples you converted json string to a list using the dumps() method.

 import json # Convert python list to JSON numbers = [25, 36, 48, 54] json_numbers = json.dumps(numbers) print(json_numbers) # Output # [25, 36, 48, 54] import json # Convert python string type list to JSON technology = ["Hadoop", "Spark", "Python"] json_string = json.dumps(technology) print(json_string) # Output # ["Hadoop", "Spark", "Python"] 

4. Convert List of Dictionaries to JSON

The json.dumps() method can be used to convert a list of dictionaries to a JSON string in python. This function converts a list of dictionaries to JSON string without losing any original data.

 import json # Convert list of dictionaries to JSON my_dict = [, ] jsondict = json.dumps(my_dict) print(jsondict) # Output # [, ] 

5. Convert a List of Lists to JSON

You can also use the json.dumps() method to convert a python list of lists to a JSON string, and this process preserves the original data in the lists. For example, JSON string representation of the list of lists, which you can then write to a file or send over a network connection, etc.

 import json # Convert a list of lists to JSON List = [[], []] jsonList = json.dumps(List) print(jsonList) # Output # [[], []] 

Conclusion

In this article, I have explained how to convert a list to JSON in python by using json.dumps() function with examples.

You may also like reading:

Источник

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" >

Источник

5 Ways to Convert Dictionary to JSON in Python

5 Ways to Convert Dictionary to JSON in Python

Most of the programs need data to work. This data is provided to the program while running or built into the program since the beginning. JSON is one of the ways to store this data in an organized and easy-to-handle manner. On the other hand, a python dictionary is one of the data types that can store a sequence of elements simultaneously in a well-formatted manner, just like JSON.

Therefore, in this article, let us understand some of the common methods to convert python Dict to JSON after a brief introduction of JSON and dictionary in python.

What is JSON in Python?

JSON(Javascript Object Notation) is a standard format to transfer the data as a text that can be sent over a network. JSON is a syntax for exchanging and storing data over the network. It uses lots of APIs and databases that are easy for humans and machines to read and understand. Python has an inbuilt package named ‘json’, which you can use to work with JSON data. To use this feature, you have to import the JSON package in python programming.

Python JSON stores the data in the form of key-value pairs inside curly brackets(<>), and hence, it is pretty similar to a python dictionary. But here, the JSON key is a string object with double quotation mark compulsorily. However, the value corresponding to the key could be of any data type, i.e., string, integer, nested JSON, or any other sequence data type similar to an array.

For Example

import json # some JSON: a = '< "name":"Jack", "age":21, "city":"California">' # parse x: b = json.loads(a) print(b["city"])

Remember that the JSON exists as a string but not a string from the data context.

What is Dictionary in Python?

Dictionary is one of the data types in python used to store the sequence of data in a single variable. Python dictionary helps store the data values like a map that is not supported by any other data type which holds only a single value as an element. Dictionary is an unordered and changeable collection of data elements stored in the form of key:value pairs inside the curly brackets(<>). Here the colon(:) represents the key associated with its respective value.

Dictionary values can be of any data type and allow duplicate values, whereas dictionary keys are unique and immutable.

For Example

sample_dict = < "vegetable": "carrot", "fruit": "orange", "chocolate": "kitkat" > print(sample_dict)

Remember that dictionary keys are case sensitive; therefore, the same name but different cases of the key will be treated distinctly.

Difference Between Dictionary and JSON

Keys can be any hashable object

Keys can be ordered and repeated

No such default value is set

Keys has a default value of undefined

Values can be accessed by subscript

Values can be accessed by using “.”(dot) or “[]”

Can use a single or double quote for the string object

The double quotation is necessary for the string object

Return ‘string’ object type

Convert Dict to JSON in Python

Below are 5 common methods you can use to convert a dict to JSON in python:

1) Using dumps() function

Python possesses a default module, ‘json,’ with an in-built function named dumps() to convert the dictionary into a JSON object by importing the «json» module. «json» module makes it easy to parse the JSON strings which contain the JSON object. The below example displays the conversion of a python dictionary to a JSON object.

For Example

import json Fruit_Dict = < 'name': 'Apple', 'color': 'Red', 'quantity': 10, 'price': 60 > Fruit_Json = json.dumps(Fruit_Dict) print(Fruit_Json)

2) Converting nested dictionary to JSON

You can create a nested dictionary in the above example by declaring a new dictionary inside the default dictionary. To convert the nested dictionary into a json object, you can use the dumps function itself. Here, we have used indent=3, which refers to the space at the beginning of the code line:

For Example

import json dictionary = < 'fruit':"Grapes": "10","color": "green">, 'vegetable':"chilli": "4","color": "red">, > result = json.dumps(dictionary, indent = 3) print(result)
  "fruit":  "Grapes": "10", "color": "green" >, "vegetable":  "chilli": "4", "Grapes": "10", >, "vegetable":  "chilli": "4", "color": "pink" > 

3) Convert dictionary to JSON quotes

You can declare a class and use it for the string representation to convert it into json object. Here, we have declared the class using the __str__(self) method, and the variable ‘collect’ is declared along with the variable ‘result’ to assign with the class and convert into the json object.

For Example

import json class fruits(dict): def __str__(self): return json.dumps(self) collect = [['apple','grapes']] result = fruits(collect) print(result)

4) Convert dictionary to JSON array

You can declare an array to check the keys and values of the dictionary and convert it into json object. The for loop stores the value, and the dumps() method stores the dictionary. Check out the below example for a better understanding of the approach.

For Example

import json dictionary = 'Apple': 3, 'Grapes': 1> array = [ 'key' : i, 'value' : dictionary[i]> for i in dictionary] print(json.dumps(array))

5) Convert dictionary to JSON using sort_keys

Using this method, you can use the sort_keys attribute inside the dumps() method and set it to “true” to sort the dictionary and convert it into json object. If you set it to false, the dictionary won’t be sorted to find the json object in python.

For Example

import json dictionary ="Name": "jack", "Branch": "IT", "CGPA": "8.6"> result = json.dumps(dictionary, indent = 3, sort_keys = True) print(result)
  "Branch": "IT", "CGPA": "8.6", "Name": "jack" > 

Conclusion

As discussed above, JSON is a data format, and a dictionary in python is a data structure. If you wish to exchange data for different processes, you should use JSON format to serialize your python dictionary. Therefore, it is essential and recommended to learn all the above methods to convert python dictionaries to a json object and make your programming easy and efficient. To learn more about conversion in python, visit our article “3 Ways to Convert List to Tuple in Python”.

Источник

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