Skip to main content
The Python packages only beautify JavaScript and CSS. HTML beautification is not supported by the Python implementation. For HTML, use the Node.js library or CLI.

Installation

Install the packages you need from PyPI:
pip install jsbeautifier

JavaScript Beautifier

Basic Usage

import jsbeautifier

result = jsbeautifier.beautify('function foo(){return 1;}')
print(result)
# function foo() {
#     return 1;
# }

Beautify from a File

import jsbeautifier

result = jsbeautifier.beautify_file('path/to/file.js')
print(result)

Custom Options

Fetch the default options object, modify the attributes you need, then pass it to beautify:
import jsbeautifier

opts = jsbeautifier.default_options()
opts.indent_size = 2
opts.space_in_empty_paren = True

result = jsbeautifier.beautify('function foo(){return 1;}', opts)
print(result)
# function foo() {
#   return 1;
# }

CSS Beautifier

Basic Usage

import cssbeautifier

result = cssbeautifier.beautify('.foo{color:red;background:blue;}')
print(result)
# .foo {
#     color: red;
#     background: blue;
# }

Custom Options

import cssbeautifier

opts = cssbeautifier.default_options()
opts.indent_size = 2
opts.end_with_newline = True

result = cssbeautifier.beautify('.foo{color:red;}', opts)
print(result)

CLI from Python Install

Installing jsbeautifier also installs the js-beautify command-line script. Beautified output goes to stdout by default:
js-beautify file.js
Write the output to a file:
js-beautify file.js -o file.pretty.js
Overwrite the input file in-place:
js-beautify -r file.js

Options Reference

Option names are the same as CLI flags with hyphens replaced by underscores. For example, --indent-size 2 --space-in-empty-paren corresponds to:
opts.indent_size = 2
opts.space_in_empty_paren = True
OptionDefaultDescription
indent_size4Spaces per indentation level
indent_char" "Character used for indentation
indent_with_tabsFalseUse tabs instead of spaces
eol"auto"Line terminator character(s) (auto = detect from file, else \n)
end_with_newlineFalseEnd output with a newline
preserve_newlinesTrueKeep existing blank lines
max_preserve_newlines10Maximum blank lines to preserve
brace_style"collapse"Brace placement style
space_in_parenFalsePad inside parens: f( a, b )
space_in_empty_parenFalseSpace inside empty parens: f( )
jslint_happyFalseEnable jslint-stricter mode
wrap_line_length0Wrap lines longer than N characters
comma_firstFalsePut commas at the start of lines