JSBeautifier Python Library
jsbeautifier is the official Python wrapper for the popular js-beautify project, providing JavaScript, HTML, and CSS code formatting and beautification capabilities. It is actively maintained with releases typically aligning with the core JavaScript library, currently at version 1.15.4.
Warnings
- gotcha The PyPI metadata for `jsbeautifier` incorrectly states `requires_python: None`. The actual minimum Python version required by `jsbeautifier` 1.15.4 and newer is Python 3.7.
- gotcha Beautifier options must be passed as an `options` object, typically initialized via `jsbeautifier.default_options()`, rather than directly as keyword arguments to `beautify()`, `html_beautify()`, or `css_beautify()`.
- gotcha The `jsbeautifier` Python package's version directly reflects the version of the underlying `js-beautify` JavaScript project. Breaking changes in the core `js-beautify` library will implicitly affect the Python wrapper, even if the Python API surface itself doesn't change.
Install
-
pip install jsbeautifier
Imports
- beautify
from jsbeautifier import beautify
- html_beautify
from jsbeautifier import html_beautify
- css_beautify
from jsbeautifier import css_beautify
- default_options
from jsbeautifier import default_options
Quickstart
import jsbeautifier
# Example for JavaScript beautification
js_code = "function test( ){ var x=1;if(x){ return x;} else { return 0;}}"
# Create and customize options object
options = jsbeautifier.default_options()
options.indent_size = 2
options.space_in_paren = True
options.keep_array_indentation = True
beautified_js = jsbeautifier.beautify(js_code, options)
print("Original JS:\n", js_code)
print("\nBeautified JS:\n", beautified_js)
# Example for HTML beautification (using the same options)
html_code = "<html><head><title>Test</title></head><body><h1>Hello</h1> <p>World</p></body></html>"
beautified_html = jsbeautifier.html_beautify(html_code, options)
print("\nOriginal HTML:\n", html_code)
print("\nBeautified HTML:\n", beautified_html)