Python json dumps example

json.dumps() in Python

JSON is an acronym that stands for JavaScript Object Notation. Despite its name, JSON is a language agnostic format that is most commonly used to transmit data between systems, and on occasion, store data. Programs written in Python, as well as many other programming languages, can ingest JSON formatted data, and can serialize data in memory into the JSON format. Python supports JSON through a built-in package called json. To use this feature, import the json package into the Python script or module in which you wish to serialize or deserialize your data. JSON utilizes comma delimited key value pairs contained in double quotes and separated by colons. The body of a JSON file can be delimited in curly braces < >or square braces [] (also known as “brackets” in some locales). The JSON format appears to be similar to the dictionary in Python, but the specifics of the JSON format have significant differences, so use care when working with both formats.

Json.dumps()

json.dumps() function will convert a subset of Python objects into a json string. Not all objects are convertible and you may need to create a dictionary of data you wish to expose before serializing to JSON.

Syntax:
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)
Parameters:
obj: Serialize obj as a JSON formatted stream
skipkeys: 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.
ensure_ascii: 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.
check_circular: If check_circular is False (default: True), then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse).
allow_nan: If allow_nan is False (default: True), then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification. If allow_nan is True, their JavaScript equivalents (NaN, Infinity, -Infinity) will be used.
indent: If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or “” will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as “\t”), that string is used to indent each level.
separators: If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘, ‘, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘, ‘, ‘:’) to eliminate whitespace.
default: If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
sort_keys: If sort_keys is True (default: False), then the output of dictionaries will be sorted by key.

Example #1: Passing the Python dictionary to json.dumps() function will return a string.

Читайте также:  Get file contents with javascript

Источник

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

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.).

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

Источник

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