Save list to file python json

Python JSON dump() and dumps() for JSON Encoding

In this article, You will learn how to use the Python json module to write Python serialized objects as JSON formatted data into file and string. The json module provides the following two methods to encode Python objects into JSON format.

  • The json.dump() method (without “s” in “dump”) used to write Python serialized object as JSON formatted data into a file.
  • The json.dumps() method encodes any Python object into JSON formatted String.

Further Reading:

The json.dump() and json.dump() is used for following operations

  • Encode Python serialized objects as JSON formatted data.
  • Encode and write Python objects into a JSON file
  • PrettyPrinted JSON data
  • Skip nonbasic types while JSON encoding
  • Perform compact encoding to save file space
  • Handle non-ASCII data while encoding JSON

Python JSON Encoding and serialization using dump and dumps

Syntax of json.dump() and json.dumps()

You can do many things using json.dump() and json.dumps() method. Let’s understand the different parameters of json.dump() to achieve different results.

Syntax of json.dump()

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)

Use: It is used to write a Python object into a file as a JSON formatted data.

Syntax of json.dumps()

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)

Use: It is used to write a Python object into a JSON String.

Parameters used:

  • obj is nothing but a Python serializable object which you want to convert into a JSON format.
  • A fp is a file pointer used to write JSON formatted data into file. Python json module always produces string objects, not bytes objects, therefore, fp.write() must support string input.
  • If skipkeys is true (default: False), then dict keys that are not of a basic type, (str, int, float, bool, None) will be skipped instead of raising a TypeError . For example, if one of your dictionary keys is a custom Python object, that key will be omitted while converting the dictionary into JSON.
  • If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
  • allow_nan is True by default so their JavaScript equivalents (NaN, Infinity, -Infinity) will be used. If False it will be a ValueError to serialize out of range float values (nan, inf, -inf).
  • An indent argument is used to pretty-print JSON to make it more readable. The default is (‘, ‘, ‘: ‘) . To get the most compact JSON representation, you should use (‘,’, ‘:’) to eliminate whitespace.
  • If sort_keys is true (default: False), then the output of dictionaries will be sorted by key
Читайте также:  Что такое iterator php

json.dumps() to convert Python primitive types into JSON equivalent

There are multiple scenarios where you need to use serialized JSON data in your program. If you need this serialized JSON data in your application of further processing then you can convert it to a native Python str object instead of writing it in a file.

For example, you receive an HTTP request to send developer detail. you fetched developer data from the database table and store it in a Python dictionary or any Python object, Now you need to send that data back to the requested application so you need to convert the Python dictionary object into a JSON formatted string to send as a response in JSON string. To do this you need to use json.dumps() .

The json.dumps() returns the JSON string representation of the Python dict . Let see the example now.

Example: Convert Python dictionary into a JSON formatted String

import json def SendJsonResponse(resultDict): print("Convert Python dictionary into JSON formatted String") developer_str = json.dumps(resultDict) print(developer_str) # sample developer dict developer_Dict = < "name": "Jane Doe", "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com" >SendJsonResponse(developer_Dict)

Writing JSON data into a Python String

Mapping between JSON and Python entities while Encoding

To encode Python objects into JSON equivalent json module uses the following conversion table. The json.dump() and json.dumps() the method performs the translations when encoding.

Now let’s see how to convert all Python primitive types such as a dict , list , set , tuple , str , numbers into JSON formatted data. Please refer to the following table to know the mapping between JSON and Python data types.

File after writing JSON encoded data using Python

Write Indented and pretty printed JSON data into a file

If the user wants to read a JSON file so it must be readable and well organized, so whoever consumes this will have a better understanding of a structure of a data. The dump() method provides the following arguments to pretty-print JSON data.

  • The indent parameter specifies the spaces that are used at the beginning of a line.
  • The separator argument of a json.dump method you can specify any separator between key and value.
  • The sort_keys to sort JSON data by keys.

Let’s see how to write pretty-printed JSON data into a file.

import json developer = < "name": "jane doe", "salary": 9000, "skills": ["Raspberry pi", "Machine Learning", "Web Development"], "email": "JaneDoe@pynative.com" >with open("developerPrettyPrint.json", "w") as write_file: json.dump(developer, write_file, indent=4, separators=(", ", ": "), sort_keys=True) print("Done writing pretty printed JSON data into a file")
Done writing pretty printed JSON data into a file

File after writing prettyprinted JSON data

Compact encoding to save file space by changing JSON key-value separator

If you are not reading a file, but you only need to write JSON data into a file to use by the underlying system or application, then you can write JSON data into a file by doing compact encoding.

We can write JSON data into a file by changing the JSON key-value separator. You can change JSON representation as per your needs. Using the separator argument of a json.dump() method you can specify any separator between key and value.

To limit the JSON file size we can remove extra spacing between JSON key-value. I have decided to do the compact encoding ( separators=(‘,’, ‘:’) ). Using this separator we can remove the whitespaces from JSON to make the JSON more compact and save bytes from being sent via HTTP. Now, Let see the example.

import json developer_dict = < "name": "jane doe", "salary": 9000, "skills": ["Raspberry pi", "Machine Learning", "Web Development"], "companies": ["Google", "Facebook", "IBM"], "email": "JaneDoe@pynative.com" >print("Started writing compact JSON data into a file") with open("developerDetailCompact.json", "w") as write_file: json.dump(developer_dict, write_file, separators=(',', ':')) print("Done writing compact JSON data into json file")
Started writing compact JSON data into a file Done writing compact JSON data into .json file

Skip nonbasic types while writing JSON into a file using skipkeys parameter

The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent (e.g., dictionary, lists, strings, ints, None, etc.).

Читайте также:  Python yield in lambda

If the Python dictionary contains a custom Python object as one of the keys and if we try to convert it into a JSON format, you will get a TypeError i.e., Object of type «Your Class» is not JSON serializable .

If this custom object isn’t required in JSON data, you can skip it using a skipkeys=true argument of the json.dump() method.
If skipkeys=true is True, then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If it is necessary to convert it into JSON, then you can refer to our article on how to Make Python class JSON Serializable.

import json class PersonalInfo: def __init__(self, name, age): self.name = name self.age = age def showInfo(self): print("Developer name is " + self.name, "Age is ", self.age) dev = PersonalInfo("John", 36) developer_Dict = < PersonalInfo: dev, "salary": 9000, "skills": ["Python", "Machine Learning", "Web Development"], "email": "jane.doe@pynative.com" >print("Writing JSON data into file by skipping non-basic types") with open("developer.json", "w") as write_file: json.dump(developer_Dict, write_file, skipkeys=True) print("Done")
Writing JSON data into file by skipping non-basic types Done

JSON file after skipping on-basic types

As you can see in the JSON output the PersonalInfo object is skipped.

Handle non-ASCII characters from JSON data while writing it into a file

The json.dump() method has ensure_ascii parameter. The ensure_ascii is by-default true. The output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is. If you want to store non-ASCII characters, as-is use the following code.

import json unicode_string = u"\u00f8" print("unicode String is ", unicode_string) # set ensure_ascii=False print("JSON character encoding by setting ensure_ascii=False") print(json.dumps(unicode_string, ensure_ascii=False))
unicode String is ø JSON character encoding by setting ensure_ascii=False "ø"

Next Steps

I want to hear from you. What do you think of this article? Or maybe I missed one of the uses of json.dump() and json.dumps() . Either way, let me know by leaving a comment below.

Also, try to solve the Python JSON Exercise to have a better understanding of Working with JSON Data in Python.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Python Write JSON to File

You can convert any Python object to a JSON string and write JSON to File using json.dumps() function and file.write() function respectively.

Читайте также:  Проверить является ли переменная числом питон

Following is a step by step process to write JSON to file.

  1. Prepare JSON string by converting a Python Object to JSON string using json.dumps() function.
  2. Create a JSON file using open(filename, ‘w’) function. We are opening file in write mode.
  3. Use file.write(text) to write JSON content prepared in step 1 to the file created in step 2.
  4. Close the JSON file.

Examples

1. Write JSON (Object) string to File

In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json.

Python Program

import json aDict = jsonString = json.dumps(aDict) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()

Run the above program, and data.json will be created in the working directory.

2. Write JSON (list of objects) to a file

In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json.

Python Program

import json aList = [, , ] jsonString = json.dumps(aList) jsonFile = open("data.json", "w") jsonFile.write(jsonString) jsonFile.close()

Run the above program, and data.json will be created in the working directory.

Summary

In this Python JSON Tutorial, we learned how to write JSON to File, using step by step process and detailed example programs.

Источник

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

Источник

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