If you are using 2.6+, you can use do this:

print json.dumps(jsonStr, sort_keys=True, indent=2, separators=(',', ': '))

http://docs.python.org/2/library/json.html

Answer from onetwopunch on Stack Overflow
Top answer
1 of 2
65

Format String Syntax section says:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

So if you want to use .format method, you need to escape all JSON curly braces in your template string:

>>> '{{"fvAp": {{"attributes": {{"name": {}}}}}}}'.format('"app-name"')
'{"fvAp": {"attributes": {"name": "app-name"}}}'

That looks really bad.

There's a better way to do that with string.Template:

>>> from string import Template
>>> t = Template('{"fvAp": {"attributes": {"name": "${name}"}}')
>>> t.substitute(name='StackOverflow')
'{"fvAp": {"attributes": {"name": "StackOverflow"}}'

Though I suggest abandoning the idea of generating configs this way altogether and using a factory function and json.dumps instead:

>>> import json
>>> def make_config(name):
...     return {'fvAp': {'attributes': {'name': name}}}
>>> app_config = make_config('StackOverflow')
>>> json.dumps(app_config)
'{"fvAp": {"attributes": {"name": "StackOverflow"}}}'
2 of 2
0

Looks like you are trying to substitute dynamic values within a json file with their runtime counterparts. You can use PLACEHOLDER in this scenario. Construct your json using PLACEHOLDER values where you would like to substitute them with dynamic values.

For example:

{
    "services": [{
            "name": "service_a",
            "config": {
                "dynamic_value_1": "PLACEHOLDER",
                "dynamic_value_2": "PLACEHOLDER"
            }
        },
        {
            "name": "service_b",
            "config": {
                "dynamic_value_1": "PLACEHOLDER",
                "dynamic_value_2": "PLACEHOLDER"
            }
        }
    ]
}

You can then read the json file and perform an update by passing a dictionary of values you want to substitute.


def dynamic_values() -> Dict:
        """
        Provides a map of placeholder values with their dynamic counterparts
        """
        return {
            "service_a": {
                "dynamic_value_1": service_a_method_1(),
                "dynamic_value_2": service_a_method_2(),
            },
            "service_b": {
                "dynamic_value_1": service_b_method_1(),
                "dynamic_value_2": service_b_method_1(),
            },
        }


def load_dynamic_values(dynamic_values) -> List:
        """
        Overrides placeholder values in json file with dynamic values at runtime
        """
        with open(file_name, "r") as f:
            data = json.load(f)

        services = data["services"]
        for s in services:
            override = dynamic_values.get(s["name"], None)
            if override:
                s["config"].update(override)
        return services
Discussions

How to format json string in Python - Stack Overflow
See docs.python.org/2/tutorial/…. 2017-10-16T17:57:35.52Z+00:00 ... Save this answer. ... Show activity on this post. If you are building these strings yourself or have control over them, have a different format be sent, or build the value as a dictionary and use json.dumps. More on stackoverflow.com
🌐 stackoverflow.com
python - String format a JSON string gives KeyError - Stack Overflow
You'd be better off just using Python dictionaries and then using json.dumps() to output the JSON format. More on stackoverflow.com
🌐 stackoverflow.com
October 20, 2020
Formatting JSON in Python - Stack Overflow
I tried with pprint, but it actually wouldn't print the pure JSON string unless it's converted to a Python dict, which loses your true, null and false etc valid JSON as mentioned in the other answer. More on stackoverflow.com
🌐 stackoverflow.com
formatting json output in Python
json.dumps(obj, indent=2, sort_keys=False) More on reddit.com
🌐 r/learnpython
16
52
May 12, 2022
People also ask

Are there online platforms for string to JSON file Python conversions?
Numerous online platforms cater to string to JSON online conversions, but it's essential to remain cautious regarding data privacy when using third-party services.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › python json – how to convert a string to json
Python JSON – How to Convert a String to JSON: Guide & Examples
How can one revert a JSON string back to its Python form?
The json.loads function in Python facilitates the decoding or deserialization of a JSON string back to its Python object form.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › python json – how to convert a string to json
Python JSON – How to Convert a String to JSON: Guide & Examples
How do you differentiate between creating a JSON string and saving it as a file in Python?
While json.dumps results in a JSON formatted string, to inscribe this string as a file in Python, one requires additional file writing functions.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › python json – how to convert a string to json
Python JSON – How to Convert a String to JSON: Guide & Examples
🌐
Reddit
reddit.com › r/learnpython › formatting json output in python
r/learnpython on Reddit: formatting json output in Python
May 12, 2022 -

Hi,

I would like to read json into Python code, and then output processed json. In order to get started with this, I have written very basic Python, and am attempting to read in very basic json I found online.

The input json is:

{
    "firstName": "John",
    "lastName": "Doe",
    "hobbies": ["biking", "coding", "rapping"],
    "age": 35,
    "children": [
        {
            "firstName": "hector",
            "age": 6
        },
        {
            "firstName": "cassandra",
            "age": 8
        }
    ]
}

The code is:

import json

if __name__ == '__main__':
    
    print( "start" )

    # read and load input json
    json_input_filename = "input.json"
    json_input = open( json_input_filename )

    json_input_dict = json.load( json_input )

    # write output json
    json_output_filename = "output.json"
    with open( json_output_filename, 'w' ) as json_output:
        json.dump( json_string, json_output )
  

    print( f"end" )

and the output is:

"{\"firstName\": \"John\", \"lastName\": \"Doe\", \"hobbies\": [\"biking\", \"coding\", \"rapping\"], \"age\": 35, \"children\": [{\"firstName\": \"hector\", \"age\": 6}, {\"firstName\": \"cassandra\", \"age\": 8}]}"

What can I do in order to preserve something resembling the original formatting? I'm going to load this output into some other code in order to process it further.

Thank you very much

🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
🌐
Medium
medium.com › @blogshub4 › how-to-pretty-print-a-json-string-in-python-98a85f99ecb4
How to Pretty Print a JSON String in Python | by Blogshub | Medium
December 22, 2024 - Pretty-printing JSON strings in Python is simple with the help of the built-in json module. By using the json.dumps() method with an indentation parameter, you can display JSON data in a more readable format.
🌐
W3Schools
w3schools.com › python › gloss_python_format_json.asp
Python Format JSON
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › json-formatting-python
JSON Formatting in Python - GeeksforGeeks
August 23, 2023 - We will be using dump(), dumps(), and JSON.Encoder class. The json.dump() method is used to write Python serialized objects as JSON formatted data into a file. The JSON. dumps() method encodes any Python object into JSON formatted String.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › python json – how to convert a string to json
Python JSON – How to Convert a String to JSON: Guide & Examples
November 18, 2024 - Then, we create a Python dictionary called data containing key-value pairs. This is the data structure we want to encode into JSON. We use the json.dumps(data) function to encode the data dictionary into a JSON-formatted string.
🌐
TutorialsPoint
tutorialspoint.com › json-formatting-in-python
Python - JSON
June 26, 2020 - encode(obj) − Serializes a Python object into a JSON formatted string.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-pretty-print-json
How to Pretty Print JSON in Python | DigitalOcean
Learn how to pretty print JSON in Python using built-in tools like json.dumps() and pprint to improve readability and debug structured data efficiently.
Top answer
1 of 3
77

You need to double the outer braces; otherwise Python thinks { "File".. is a reference too:

output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'

Result:

>>> print output_format.format(filename='My_file_name',
...                            success=True,
...                            error_msg='',
...                            log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }

If, indicentally, you are producing JSON output, you'd be better off using the json module:

>>> import json
>>> print json.dumps({'File': 'My_file_name',
...                   'Success': True,
...                   'ErrorMessage': '',
...                   'LogIdentifier': '123'})
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}

Note the lowercase true in the output, as required by the JSON standard.

2 of 3
4

As mentioned by Tudor in a comment to another answer, the Template class was the solution that worked best for me. I'm dealing with nested dictionaries or list of dictionaries and handling those were not as straightforward.

Using Template though the solution is quite simple.

I start with a dictionary that is converted into a string. I then replace all instances of { with ${ which is the Template identifier to substitute a placeholder.

The key point of getting this to work is using the Template method safe_substitute. It will replace all valid placeholders like ${user_id} but ignore any invalid ones that are part of the dictionary structure, like ${'name': 'John', ....

After the substitution is done I remove any leftovers $ and convert the string back to a dictionary.

In the code bellow, resolve_placeholders returns a dictionary where each key matches a placeholder in the payload string and the value is substituted by the Template class.

from string import Template
.
.
.
payload = json.dumps(payload)
payload = payload.replace('{', '${')
replace_values = self.resolve_placeholders(payload)
if replace_values:
    string_template = Template(payload)
    payload = string_template.safe_substitute(replace_values)
payload = payload.replace('${', '{')
payload = json.loads(payload)
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.7 documentation
If zero, negative, or "" (the empty string), only newlines are inserted. If None (the default), no newlines are inserted. separators (tuple | None) – A two-tuple: (item_separator, key_separator). If None (the default), separators defaults to (', ', ': ') if indent is None, and (',', ': ') otherwise. For the most compact JSON, specify (',', ':') to eliminate whitespace.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-pretty-print-json
Python - Pretty Print JSON - GeeksforGeeks
July 23, 2025 - This code reads JSON data from a file called "test.json," parses it into a Python data structure, and then prints it using both the built-in print function and the pprint module. The pprint module is used to pretty-print the JSON data with specific formatting options like an indentation of 2, a line width of 30 characters, and compact representation.
Top answer
1 of 2
11

json.dumps(obj, indent=2) is better than pprint because:

  1. It is faster with the same load methodology.
  2. It has the same or similar simplicity.
  3. The output will produce valid JSON, whereas pprint will not.

pprint_vs_dumps.py

import cProfile
import json
import pprint
from urllib.request import urlopen


def custom_pretty_print():
    url_to_read = "https://www.cbcmusic.ca/Component/Playlog/GetPlaylog?stationId=96&date=2018-11-05"
    with urlopen(url_to_read) as resp:
        pretty_json = json.dumps(json.load(resp), indent=2)
    print(f'Pretty: {pretty_json}')


def pprint_json():
    url_to_read = "https://www.cbcmusic.ca/Component/Playlog/GetPlaylog?stationId=96&date=2018-11-05"
    with urlopen(url_to_read) as resp:
        info = json.load(resp)
    pprint.pprint(info)


cProfile.run('custom_pretty_print()')
>>> 71027 function calls (42309 primitive calls) in 0.084 seconds

cProfile.run('pprint_json()')
>>>164241 function calls (140121 primitive calls) in 0.208 seconds

Thanks @tobias_k for pointing out my errors along the way.

2 of 2
3

I think for a true JSON object print, it's probably as good as it gets. timeit(number=10000) for the following took about 5.659214497s:

import json
d = {   
        'breakfast': [
            'spam', 'spam', 'eggs', 
            {
                'another': 'level', 
                'nested': [
                    {'a':'b'}, 
                    {'c':'d'}
                ]
            }
        ], 
        'foo': True,
        'bar': None
    }
s = json.dumps(d)
q = json.dumps(json.loads(s), indent=2)
print(q)

I tried with pprint, but it actually wouldn't print the pure JSON string unless it's converted to a Python dict, which loses your true, null and false etc valid JSON as mentioned in the other answer. As well it doesn't retain the order in which the items appeared, so it's not great if order is important for readability.

Just for fun I whipped up the following function:

def pretty_json_for_savages(j, indentor='  '):
    ind_lvl = 0
    temp = ''
    for i, c in enumerate(j):
        if c in '{[':
            print(indentor*ind_lvl + temp.strip() + c)
            ind_lvl += 1
            temp = ''
        elif c in '}]':
            print(indentor*ind_lvl + temp.strip() + '\n' + indentor*(ind_lvl-1) + c, end='')
            ind_lvl -= 1
            temp = ''
        elif c in ',':
            print(indentor*(0 if j[i-1] in '{}[]' else ind_lvl) + temp.strip() + c)
            temp = ''
        else:
            temp += c
    print('')

# {
#   "breakfast":[
#     "spam",
#     "spam",
#     "eggs",
#     {
#       "another": "level",
#       "nested":[
#         {
#           "a": "b"
#         },
#         {
#           "c": "d"
#         }        
#       ]      
#     }    
#   ],
#   "foo": true,
#   "bar": null
# }

It prints pretty alright, and unsurprisingly it took a whooping 16.701202023s to run in timeit(number=10000), which is 3 times as much as a json.dumps(json.loads()) would get you. It's probably not worthwhile to build your own function to achieve this unless you spend some time to optimize it, and with the lack of a builtin for the same, it's probably best you stick with your gun since your efforts will most likely give diminishing returns.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-pretty-print-json-in-python
How to Pretty Print JSON in Python
April 14, 2023 - To pretty print JSON in Python, we can use the built-in json module. This module provides a dumps() function that can serialize Python objects into a JSON formatted string.
🌐
ReqBin
reqbin.com › code › python › 0l6wsqxp › python-pretty-print-json-example
How do I pretty print JSON in Python?
To pretty print a JSON string in Python, you can use the json.dumps(indent) method of the built-in package named json. First, you need to use the json.loads() method to convert the JSON string into a Python object.
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - When you set skipkeys in json.dumps() to True, then Python skips the keys that are not supported and would otherwise raise a TypeError. The result is a JSON-formatted string that only contains a subset of the input dictionary. In practice, you usually want your JSON data to resemble the input object as close as possible.
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
The dumps() method converts a Python object to a JSON formatted string. We can also create a JSON file from data stored in a Python dictionary.