Ask Your Question
1

How can I eliminate the white spaces in a JSON file generated by Python?

asked 2023-07-12 00:03:41 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-12 00:33:02 +0000

pufferfish gravatar image

You can use the json.dumps() function with the separators parameter to eliminate white spaces in a JSON file generated by Python.

The separators parameter is a tuple that specifies the characters used to separate the items in the JSON string. The first character of the tuple represents the separator between items (usually a comma), while the second character represents the separator between keys and values (usually a colon).

Here's an example of how to use json.dumps() with the separators parameter:

import json

data = {"name": "John", "age": 30, "city": "New York"}

# Dump the data to a JSON string without white spaces
json_str = json.dumps(data, separators=(",", ":"))

# Print the JSON string
print(json_str)

Output:

{"name":"John","age":30,"city":"New York"}

As you can see, the resulting JSON string has no white spaces between the items.

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: 2023-07-12 00:03:41 +0000

Seen: 12 times

Last updated: Jul 12 '23