What is JSON?
JavaScript Object Notation (JSON) is a standard text format for representing structured data using JavaScript syntax. JSON is often used in mobile and web applications to exchange and store data. JSON data is much smaller than XML and easier for humans and computers to read. Most scripting languages use JSON, including JavaScript, Java, Python, C++, C#, Go, PHP, and many more. JSON files are named with the .json extension.
Python json.dump() method
The json.dump() method converts (encodes) Python object to JSON string and writes it to a file.
Where:
- dict: the Python object to be converted to a JSON data string
- file_pointer: the pointer to a file opened in write or append mode
Python json.dumps() method
The json.dumps() method is used in Python to convert an object to a JSON string.
Where:
- dict: the Python object to be converted to a JSON data string
- indent: the parameter defines the number of units to indent
What is Python Object Serialization?
In programming, serialization is the process of converting (encoding) objects into a stream of bytes (or string) for storing them in a database or file or transferring them over the network. Serialization preserves the state of an object so that it can be recreated in an identical state when needed. Serialization itself is insecure, and Python objects containing sensitive data must be additionally protected and transmitted only over secure network connections.
What are the main differences between json.dump() and json.dumps()?
The following table shows the main differences between json.dump() and json.dumps()
json.dump() | json.dumps() |
---|---|
The json.dump() method is used to write a serialized Python object as JSON data to a file | The json.dumps() method is used to encode any Python object into a JSON string |
The json.dump() method performs compact encoding to save file space | The json.dumps() method returns a string representation of a JSON dict Python |
The json.dump() method is used on a standard non-standard type when encoding JSON | The json.dumps() method can be used with lists |
How does JSON Encoder convert Python object to JSON string?
Since JSON is an independent data storage format and comes from the world of JavaScript, it has different data types than Python. JSON encoders support only the following data structures and types, and throw exceptions for objects using other Python types:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |