Hjson
Hjson is a syntax extension to JSON, designed as a human-friendly configuration file format. It allows for comments, multiline strings, and optional quotes, aiming to reduce common errors made by humans when writing JSON. The Python implementation, `hjson-py`, is based on `simplejson` and is currently at version 3.1.0.
Warnings
- gotcha Quoteless strings in Hjson automatically end at the newline. Preceding and trailing whitespace is ignored, and escapes are not supported. Additionally, a quoteless string cannot start with a comment sequence (`#`, `//`, `/*`), as these characters would become part of the string or be misinterpreted.
- gotcha Hjson's relaxed syntax can introduce ambiguity, particularly with quoteless strings that resemble booleans or numbers. For example, `true` is parsed as a boolean, but `True` (with a capital 'T') is parsed as a string, because it's not a recognized boolean literal in Hjson.
- gotcha When parsing Hjson, if the root object's opening brace `{` is on the same line as its first key-value pair without a preceding newline, the Python parser might error or misinterpret the structure. While not explicitly in official docs as a bug, it's a reported parsing quirk.
- deprecated For `hjson.dumps()`, the `indent` parameter in versions prior to 2.1.0 accepted an integer, which was then converted to a string of spaces. While still supported for backwards compatibility, it is now recommended to pass a string (e.g., `' '`) for indentation.
- gotcha Hjson allows omitting curly braces `{}` for the root object, similar to YAML, making configuration files simpler. However, this feature might not be universally supported by all third-party Hjson implementations.
- gotcha The `hjson.dumpsJSON()` function, which converts Python objects to strict JSON, is noted in the documentation to be 'probably not as performant as the `simplejson` version'. If performance is critical for JSON output, consider using `json.dumps` from the standard `json` module or `simplejson.dumps` directly.
Install
-
pip install hjson
Imports
- hjson
import hjson
- loads
hjson.loads(hjson_string)
- dumps
hjson.dumps(python_object)
- dumpsJSON
hjson.dumpsJSON(python_object)
Quickstart
import hjson
import collections
# Decoding Hjson
hjson_text = '''
{
foo: a # This is a comment
bar: 1
# Multiline string example
description: '''
This is a
multiline string.
'''
}
'''
# Parse Hjson string
data = hjson.loads(hjson_text)
print(f"Decoded Hjson: {data}")
assert data == collections.OrderedDict([
('foo', 'a'),
('bar', 1),
('description', 'This is a\nmultiline string.\n')
])
# Encoding Python object hierarchies to Hjson
python_obj = {'foo': 'text', 'bar': [1, 2], 'nested': {'key': 'value'}}
hjson_output = hjson.dumps(python_obj, indent=2)
print(f"\nEncoded Hjson:\n{hjson_output}")
# Encoding to strict JSON (note: may be less performant than simplejson)
json_output = hjson.dumpsJSON(python_obj, indent=2)
print(f"\nEncoded JSON:\n{json_output}")