You can use the json.dumps()
function with the default
argument to customize the serialization of the JSON object.
Here's an example. Suppose you have a dictionary my_dict
with several columns, and you want to include only two of them (e.g., "col1" and "col2") in the JSON output:
import json
my_dict = {
"col1": "foo",
"col2": 42,
"col3": [1, 2, 3]
}
# Define a function to filter out unwanted columns
def filter_columns(obj):
return {k: obj[k] for k in obj if k in {"col1", "col2"}}
# Use the `default` argument with the filtering function
json_output = json.dumps(my_dict, default=filter_columns)
print(json_output)
# Output: {"col1": "foo", "col2": 42}
In this example, the filter_columns()
function takes an object as input (in this case, the my_dict
dictionary), and returns a new dictionary with only the "col1" and "col2" keys (using a set intersection).
The default
argument of json.dumps()
is called for each element of the input and is used to serialize non-standard objects (like dictionaries). By passing our filtering function to default
, we tell json.dumps()
to use it for the serialization of the my_dict
dictionary, effectively filtering out unwanted columns.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-12-28 11:00:00 +0000
Seen: 11 times
Last updated: Jun 30 '21
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?