Skip to the content.

API Reference

Complete API documentation for Valheim Save Tools Python API.

Table of Contents


Core Class

ValheimSaveTools

ValheimSaveTools(
    jar_path: Optional[str] = None,
    java_path: Optional[str] = None,
    verbose: bool = False,
    fail_on_unsupported_version: bool = False,
    skip_resolve_names: bool = False
)

Main API class for interacting with Valheim save files.

Parameters:

Example:

from valheim_save_tools_py import ValheimSaveTools

# Basic initialization
vst = ValheimSaveTools()

# With verbose output
vst = ValheimSaveTools(verbose=True)

# With custom JAR path
vst = ValheimSaveTools(jar_path="/path/to/valheim-save-tools.jar")

File Conversion Methods

to_json()

to_json(
    input_file: Union[str, BinaryIO],
    output_file: Union[str, BinaryIO, None] = None
) -> Dict

Convert Valheim save file to JSON format and return parsed data.

Supported formats: .db, .fwl, .fch

Parameters:

Returns: Dictionary containing the parsed JSON data from the save file

Raises:

Example:

# Get JSON data directly
data = vst.to_json("world.db")
print(f"World version: {data['version']}")
print(f"Global keys: {data.get('globalKeys', [])}")

# Save to file and get data
data = vst.to_json("world.db", "backup.json")

# Convert character file
char_data = vst.to_json("character.fch")
print(f"Character name: {char_data.get('name', 'Unknown')}")

# Using file-like objects (BytesIO)
from io import BytesIO

# Read from BytesIO
with open("world.db", "rb") as f:
    db_data = BytesIO(f.read())
data = vst.to_json(db_data)

# Write to BytesIO
json_output = BytesIO()
data = vst.to_json("world.db", json_output)
json_output.seek(0)
json_content = json_output.read()

from_json()

from_json(
    input_file: Union[str, BinaryIO],
    output_file: Union[str, BinaryIO, None] = None
) -> Union[str, None]

Convert JSON back to binary save format.

Parameters:

Returns:

Raises:

Example:

# Auto-generate output filename
vst.from_json("world.json")  # Creates world.db

# Explicit output filename
vst.from_json("backup.json", "world_restored.db")

# Using file-like objects
from io import BytesIO

# Read JSON from BytesIO
json_data = BytesIO(b'{"version": 34, ...}')
result_path = vst.from_json(json_data, "world.db")

# Write to BytesIO
with open("backup.json", "rb") as f:
    json_input = BytesIO(f.read())

db_output = BytesIO()
vst.from_json(json_input, db_output)
db_output.seek(0)
# Now db_output contains the .db file data

Item Parsing

parse_items_from_base64()

parse_items_from_base64(b64_string: str) -> List[Dict]

Parse Valheim inventory/item data from base64-encoded binary format.

Parameters:

Returns: List of item dictionaries, each containing:

Raises:

Example:

from valheim_save_tools_py import parse_items_from_base64

# Parse inventory data
base64_data = "AQAAAAIAAAAKQXhlQnJvbnpl..."
items = parse_items_from_base64(base64_data)

# Display items
for item in items:
    print(f"Item: {item['name']}")
    print(f"  Stack: {item['stack']}")
    print(f"  Durability: {item['durability']:.1f}")
    print(f"  Quality: {item['quality']}")
    print(f"  Equipped: {item['equipped']}")
    if item['crafter_name']:
        print(f"  Crafted by: {item['crafter_name']}")

# Filter equipped items
equipped = [item for item in items if item['equipped']]
print(f"Equipped items: {len(equipped)}")

# Check for specific items
weapons = [item for item in items if 'Sword' in item['name'] or 'Bow' in item['name']]

ValheimItemReader

ValheimItemReader(data: bytes)

Low-level binary reader for parsing Valheim item data structures.

Parameters:

Attributes:

Methods:

read_byte() -> int

Read a single byte and advance offset.

read_int32() -> int

Read a 4-byte signed integer (little-endian).

read_int64() -> int

Read an 8-byte signed long (little-endian).

read_float() -> float

Read a 4-byte floating-point number (little-endian).

read_bool() -> bool

Read a boolean value (1 byte, True if non-zero).

read_string() -> str

Read a length-prefixed UTF-8 string (1-byte length prefix).

read_item() -> Dict

Read a complete Valheim item structure and return as dictionary.

Example:

from valheim_save_tools_py import ValheimItemReader
import base64

# Decode base64 data
binary_data = base64.b64decode(base64_string)

# Create reader
reader = ValheimItemReader(binary_data)

# Read header
version = reader.read_int32()
num_items = reader.read_int32()

# Read items manually
items = []
for i in range(num_items):
    item = reader.read_item()
    items.append(item)

print(f"Version: {version}")
print(f"Found {len(items)} items")

Use Case:

The ValheimItemReader class is useful when you need fine-grained control over parsing or when working with custom binary formats. For most use cases, the parse_items_from_base64() function is more convenient.


Global Keys Methods

list_global_keys()

list_global_keys(db_file: str) -> List[str]

List all global keys in a world.

Parameters:

Returns: List of global key strings

Raises:

Example:

keys = vst.list_global_keys("world.db")
print(f"Global keys: {keys}")

# Check if boss defeated
if "defeated_eikthyr" in keys:
    print("Eikthyr has been defeated!")

add_global_key()

add_global_key(db_file: str, key: str) -> None

Add a global key to the world.

Parameters:

Raises:

Common Keys:

Example:

# Add boss defeat
vst.add_global_key("world.db", "defeated_eikthyr")

# Add multiple keys
for boss in ["defeated_eikthyr", "defeated_gdking", "defeated_bonemass"]:
    vst.add_global_key("world.db", boss)

remove_global_key()

remove_global_key(db_file: str, key: str) -> None

Remove a specific global key.

Parameters:

Raises:

Example:

vst.remove_global_key("world.db", "defeated_eikthyr")

clear_all_global_keys()

clear_all_global_keys(db_file: str) -> None

Remove all global keys from the world.

Parameters:

Raises:

Example:

vst.clear_all_global_keys("world.db")

Structure Processing Methods

clean_structures()

clean_structures(db_file: str, threshold: int = 25) -> None

Clean abandoned structures based on distance threshold.

Parameters:

Raises:

Example:

# Default threshold
vst.clean_structures("world.db")

# Conservative cleaning
vst.clean_structures("world.db", threshold=10)

# Aggressive cleaning
vst.clean_structures("world.db", threshold=50)

reset_world()

reset_world(db_file: str) -> None

Reset world to initial state.

Parameters:

Raises:

Example:

vst.reset_world("world.db")

Builder Pattern

process()

process(input_file: str) -> SaveFileProcessor

Create a processor for chaining operations.

Parameters:

Returns: SaveFileProcessor instance

Raises:

Example:

# Method chaining
result = (vst.process("world.db")
             .clean_structures(threshold=30)
             .reset_world()
             .add_global_key("defeated_eikthyr")
             .save("cleaned_world.db"))

# Export to JSON after processing
json_file = (vst.process("world.db")
                .clean_structures()
                .to_json("cleaned_world.json"))

# Context manager
with vst.process("world.db") as processor:
    processor.clean_structures()
    processor.reset_world()
# Automatically saves to original file

SaveFileProcessor Methods

clean_structures(threshold: int = 25)

Queue structure cleaning operation.

reset_world()

Queue world reset operation.

add_global_key(key: str)

Queue global key addition.

remove_global_key(key: str)

Queue global key removal.

clear_all_global_keys()

Queue clearing all global keys.

save(output_file: Optional[str] = None) -> str

Execute all operations and save result.

to_json(output_file: Optional[str] = None) -> Dict

Execute all operations and convert result to JSON.

Example:

# Get data after cleaning
data = vst.process("world.db").clean_structures().to_json()
print(f"Cleaned world data: {data}")

# Also save to file
data = vst.process("world.db").clean_structures().to_json("output.json")

File Detection Methods

All file detection methods are static and can be called without instantiating the class.

is_db_file()

@staticmethod
is_db_file(file_path: str) -> bool

Check if file is a .db file.

Example:

if ValheimSaveTools.is_db_file("world.db"):
    print("Valid world data file")

is_fwl_file()

@staticmethod
is_fwl_file(file_path: str) -> bool

Check if file is a .fwl file.

is_fch_file()

@staticmethod
is_fch_file(file_path: str) -> bool

Check if file is a .fch file (character file).

is_json_file()

@staticmethod
is_json_file(file_path: str) -> bool

Check if file is a .json file.

detect_file_type()

@staticmethod
detect_file_type(file_path: str) -> Optional[str]

Detect file type from extension.

Returns: "db", "fwl", "fch", "json", or None if unknown

Example:

file_type = ValheimSaveTools.detect_file_type("world.db")
print(f"File type: {file_type}")  # Output: db

is_valheim_file()

@staticmethod
is_valheim_file(file_path: str) -> bool

Check if file is any Valheim save file type (.db, .fwl, .fch, or .json).

Example:

if ValheimSaveTools.is_valheim_file("world.db"):
    print("This is a Valheim file")

Error Handling

Exception Hierarchy

ValheimSaveToolsError          # Base exception
├── JarNotFoundError           # JAR file not found
├── JavaNotFoundError          # Java not installed
└── CommandExecutionError      # Command execution failed

Usage Example

from valheim_save_tools_py import (
    ValheimSaveTools,
    JarNotFoundError,
    JavaNotFoundError,
    CommandExecutionError
)

try:
    vst = ValheimSaveTools()
    vst.clean_structures("world.db")
except JarNotFoundError:
    print("JAR file not found!")
except JavaNotFoundError:
    print("Java is not installed!")
except CommandExecutionError as e:
    print(f"Command failed: {e}")
except ValueError as e:
    print(f"Invalid input: {e}")

Common Errors

ValueError: “not a valid .db file”

JarNotFoundError

JavaNotFoundError

CommandExecutionError