Skip to content

Converters

Chris Griffith edited this page Nov 4, 2026 · 3 revisions
Converter Method Description
to_dict Recursively transform all Box (and BoxList) objects back into a dict (and lists)
to_json Save Box object as a JSON string or write to a file with the filename parameter
to_yaml Save Box object as a YAML string or write to a file with the filename parameter
to_msgpack Save Box object as msgpack bytes or write to a file with the filename parameter
to_toml* Save Box object as a TOML string or write to a file with the filename parameter
to_csv** Save BoxList object as a CSV string or write to a file with the filename parameter
from_json Classmethod, Create a Box object from a JSON file or string (all Box parameters can be passed)
from_yaml Classmethod, Create a Box object from a YAML file or string (all Box parameters can be passed)
from_msgpack Classmethod, Create a Box object from a msgpack file or bytes (all Box parameters can be passed)
from_toml* Classmethod, Create a Box object from a TOML file or string (all Box parameters can be passed)
from_csv** Classmethod, Create a BoxList object from a CSV file or string (all BoxList parameters can be passed)

* Do not work with BoxList, only Box

** Do not work with Box, only BoxList

Loading any file

box_from_file picks the right loader from the file extension and returns a Box or a BoxList, depending on what the file holds.

from box import box_from_file

config = box_from_file("config.yaml")
servers = box_from_file("servers.json")

# Pass file_type when the extension doesn't say what it is
config = box_from_file("config.txt", file_type="yaml")

# Box options are passed through
config = box_from_file("config.yaml", default_box=True)
Extension Format
json, jsn JSON
yaml, yml YAML
toml, tml TOML
msgpack, pack msgpack
csv CSV (always a BoxList)
toon TOON

To load more values into a Box you already have, merge them in:

config = box_from_file("defaults.yaml")
config.merge_update(box_from_file("plugin.yaml"))

box_from_string(content, string_type="json") does the same for a string, with string_type of json, toml or yaml.

YAML

to_yaml uses ruamel.yaml if it is installed, otherwise PyYAML.

Changed in Box 8: keys are written in insertion order with every YAML backend. Before Box 8, PyYAML and the ruamel safe / unsafe dumpers sorted keys alphabetically. Pass sort_keys=True to sort them.

my_box = Box(zlast=1, afirst=2)

print(my_box.to_yaml())
# zlast: 1
# afirst: 2

print(my_box.to_yaml(sort_keys=True, ruamel_typ="safe"))
# afirst: 2
# zlast: 1

The default ruamel round trip dumper (ruamel_typ="rt") always keeps insertion order.

Clone this wiki locally