Python write json with double quotes

I see that the OP wanted JSON, but I do not want JSON and pprint is so close to giving me what I do want: black-compatible Python source, which requires that I use " instead of '.

I settled on .replace("'", '"') with pformat(), although this is both ugly and fragile ☹️:

import pprint

# Note: my code auto-generates my_dict parsing a file (not black-formatted here)
my_dict = ["spam", "eggs", "lumberjack", "knights", "ni", "eggs", "lumberjack", "knights", "ni"]

pprinter = pprint.PrettyPrinter(indent=4)
formatted_code = (
    pprinter.pformat(my_dict)
    .replace("[ ", "[\n  ")  # break after opening bracket
    .replace("']", "',\n]")  # break before closing bracket, add comma
    .replace("'", '"')  # use double quotes
)
with open("example_module.py", "w", encoding="utf-8") as outfile:
    outfile.write('"""Module containing auto-generated ALL_MR_HEADERS."""\n')
    outfile.write(f"ALL_MR_HEADERS = {formatted_code}\n")

The resulting example_module.py is black-compliant.

Last update on August 19 2022 21:51:40 (UTC/GMT +8 hours)

Python Basic: Exercise-130 with Solution

Write a Python program to use double quotes to display strings.

Pictorial Presentation:

Python write json with double quotes

Sample Solution:-

Python Code:

import json
print(json.dumps({'Alex': 1, 'Suresh': 2, 'Agnessa': 3}))

Sample Output:

{"Agnessa": 3, "Alex": 1, "Suresh": 2}

Flowchart:

Python write json with double quotes

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to add leading zeroes to a string.
Next: Write a Python program to split a variable length string into variables.

Python: Tips of the Day

Combining two iterable of tuples or pivot nested iterables:

# Combining two iterables
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]

# Pivoting list of tuples
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]

convert single quote json data file to double quote json data file (without mangling inner quotes)

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

__author__ = 'mbrzustowicz'
# metadata.json has single quotes like this
# {'asin': 'B00M0AEPXG', 'imUrl': 'http://ecx.images-amazon.com/images/I/51hcXTUeHLL._BO2,204,203,200_ ..... }
# so the strategy is to read each line as a string, and dump into a REAL json file
import json
import ast
fr=open("/Users/mbrzustowicz/Downloads/metadata.json")
fw=open("/Users/mbrzustowicz/amazon_product_metadata.json", "w")
for line in fr:
json_dat = json.dumps(ast.literal_eval(line))
dict_dat = json.loads(json_dat)
json.dump(dict_dat, fw)
fw.write("\n")
fw.close()
fr.close()

How do I allow double quotes in JSON?

If you're making a . json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes: \" is the one you're looking for.

Can you use a double quote inside a JSON string?

Can you use a double quote inside a JSON string? Yes, if you use the ascii code.

Is JSON single quote or double quote?

Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .

Should JSON be double quotes?

JSON names require double quotes.