Registry / serialization / javaproperties

javaproperties

JSON →
library0.8.2pypypi✓ verified 23d ago

javaproperties is a Python library that provides comprehensive support for reading and writing Java `.properties` files, encompassing both the simple line-oriented format and XML. It offers a straightforward API inspired by Python's `json` module, alongside a `Properties` class designed to emulate the behavior of Java 8's `java.util.Properties` as closely as possible in Python. The library is actively maintained, with the latest version 0.8.2 released in December 2024, and its release cadence is irregular, with significant gaps between major versions.

pip install javaproperties
INSTALL
IMPORT
SIG · JAVAPROPERTIES
J
javaproperties
serializationpythonv0.8.2
Install
1.6s avg
Import
191ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.8.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.200s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.182s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

dumps
from javaproperties import dumps
Function to serialize a Python dict to a .properties string.
loads
from javaproperties import loads
Function to deserialize a .properties string to a Python dict.
dump
from javaproperties import dump
Function to serialize a Python dict to a file-like object.
load
from javaproperties import load
Function to deserialize a file-like object to a Python dict.
Properties
from javaproperties import Properties
Class mimicking Java's java.util.Properties, providing dictionary-like interface with additional methods.

This quickstart demonstrates how to use `javaproperties` to serialize Python dictionaries to Java `.properties` strings and files, and deserialize them back. It also shows the usage of the `Properties` class, which offers an API similar to Java's `java.util.Properties`.

import javaproperties import io # Example data to work with data = { "key": "value", "host:port": "127.0.0.1:80", "snowman": "☃", "goat": "🐐", "multiline_value": "line1\\nline2" } # 1. Serialize a Python dictionary to a .properties string print("--- DUMPING TO STRING ---") properties_string = javaproperties.dumps(data, sort_keys=True, timestamp=None) print(properties_string) # 2. Deserialize a .properties string back to a Python dictionary print("\n--- LOADING FROM STRING ---") loaded_data_string = javaproperties.loads(properties_string) print(loaded_data_string) # 3. Serialize to a file-like object (using StringIO for demonstration) print("\n--- DUMPING TO/LOADING FROM FILE ---") with io.StringIO() as fp: javaproperties.dump(data, fp, sort_keys=True, timestamp=None, encoding='latin-1') fp.seek(0) # Rewind to beginning to read file_content = fp.read() print("File content:\n", file_content) fp.seek(0) # Rewind again for loading loaded_data_file = javaproperties.load(fp, encoding='latin-1') print("Loaded from file:", loaded_data_file) # 4. Using the Properties class (Java-like interface) print("\n--- USING PROPERTIES CLASS ---") props = javaproperties.Properties() props.update(data) print(f"Properties object (dict-like): {props}") print(f"Value for 'snowman': {props.get('snowman')}") # Storing to a file with Properties class with io.StringIO() as fp_props: props.store(fp_props, timestamp=None, encoding='latin-1') fp_props.seek(0) print("Properties class output:\n", fp_props.read())
Debug
Known issues
breakingVersion 0.8.0 dropped support for Python 2.7, 3.4, and 3.5. Users on these Python versions must upgrade to Python 3.8+ (or 3.10+ for 0.8.2).
fix
Upgrade your Python environment to 3.10 or newer. Check the PyPI page for the exact `Requires-Python` metadata if using older `javaproperties` versions.
affects: >=0.8.0
breakingIn version 0.7.0, the `javaproperties.parse()` function's return type changed from triples of strings to a generator of custom `PropertiesElement` objects. Code relying on the old return structure will break.
fix
Update code to iterate over the `PropertiesElement` objects returned by `parse()` and access their attributes (e.g., `element.key`, `element.value`, `element.source`).
affects: >=0.7.0
breakingAs of version 0.5.0, parsing invalid `\uXXXX` escape sequences will now raise an `InvalidUEscapeError` instead of potentially silently failing or producing incorrect output.
fix
Ensure that any input `.properties` files are correctly formatted, especially concerning Unicode escape sequences. Implement error handling for `InvalidUEscapeError` if processing untrusted input.
affects: >=0.5.0
gotchaThe command-line interface (CLI) tools (e.g., `javaproperties`, `json2properties`, `properties2json`) were split into a separate `javaproperties-cli` package as of version 0.4.0.
fix
If you relied on the CLI tools, you need to install the `javaproperties-cli` package separately: `pip install javaproperties-cli`.
affects: >=0.4.0
gotchaStarting with version 0.8.0, the `Properties` and `PropertiesFile` classes no longer explicitly raise `TypeError` when given non-string keys or values. The library now relies on static type checking to enforce type correctness.
fix
Ensure all keys and values passed to `Properties` or `PropertiesFile` instances are strings. Utilize static type checkers (like MyPy) in your development workflow to catch type mismatches proactively.
affects: >=0.8.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'javaproperties'
The `javaproperties` library has not been installed in your Python environment.
fix
Install the library using pip: `pip install javaproperties`
UnicodeEncodeError: 'latin-1' codec can't encode character '\uXXXX' in position XX: ordinal not in range(256)
You are trying to write a `.properties` file with characters outside the ISO-8859-1 (Latin-1) encoding, which is the default for Java .properties files, without proper escaping or specifying a different encoding.
fix
When writing, ensure non-Latin-1 characters are Unicode-escaped (the library handles this by default for the standard format), or explicitly specify `xml=True` for UTF-8 encoding (which uses the XML format) if your data contains such characters: 
```python
import javaproperties

# For standard .properties, non-Latin-1 characters are automatically escaped
props = {'key': 'value with non-ASCII char: éàç'}
with open('config.properties', 'w', encoding='latin-1') as fp:
    javaproperties.dump(props, fp)

# For XML format, UTF-8 is the default and supports all Unicode characters
props_xml = {'key': 'value with non-ASCII char: éàç'}
with open('config.xml', 'wb') as fp:
    javaproperties.dump(props_xml, fp, xml=True)
```
javaproperties.api.FormatError: Malformed property line: 'invalid_key: = value'
The `.properties` file being read contains a syntax error or is malformed according to the Java .properties file specification, which the `javaproperties` library严格 adheres to. Common issues include incorrect escaping, duplicate keys in certain contexts, or malformed lines.
fix
Review the `.properties` file for syntax errors such as unescaped special characters (e.g., `:`, `=`, `!`, `#` at the start of a line), incorrect line continuations, or other formatting issues. Ensure that keys and values are properly formed. For example, if you have a colon in your key, it must be escaped if it's not meant as a separator: `key\:with\:colon=value`
TypeError: write() argument must be str, not bytes
You are trying to write to a file opened in binary mode (`'wb'`) when `javaproperties.dump` is expecting a text stream (for the default line-oriented format), or conversely, trying to write bytes to a text stream when using `xml=True` which requires a binary stream.
fix
Open the file with the correct mode and encoding: use `'w'` (text mode) with a suitable `encoding` (like `'latin-1'`) for standard `.properties` files, and `'wb'` (binary mode) for XML properties files (`xml=True`).
```python
import javaproperties

# For standard .properties (text mode, latin-1 encoding)
props = {'my_key': 'my_value'}
with open('config.properties', 'w', encoding='latin-1') as fp:
    javaproperties.dump(props, fp)

# For XML properties (binary mode)
props_xml = {'my_key': 'my_value_xml'}
with open('config.xml', 'wb') as fp:
    javaproperties.dump(props_xml, fp, xml=True)
```
import properties # instead of javaproperties
You are attempting to import a different, unrelated Python package named `properties` (or `jproperties`) instead of the `javaproperties` library.
fix
Correct the import statement to specifically use the `javaproperties` library:
```python
import javaproperties
# or
from javaproperties import load, dump, Properties
```
Upgrade
Version history
0.8.2latest on PyPI · released Dec 1, 2024
Audit
Dependencies
pythonrequiredRequires Python 3.10 or higher as of version 0.8.2.
Agent activity
4 hits · last 30 days
node
3
Resources
javaproperties — pip install javaproperties · libregistry