Ask Your Question
2

How can I choose certain columns in python's json.dumps() function?

asked 2021-12-28 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-06-30 17:00:00 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-12-28 11:00:00 +0000

Seen: 11 times

Last updated: Jun 30 '21