Reading and writing structured_metadata
structured_metadata is free-form nested JSON kept in an entry's metadata. Use it to store a full set of instrument settings, or a per-measurement metadata file (YAML / JSON), without splitting it into fields. This page covers reading and writing, converting to and from a flat "key = value" list, and checking against a schema.
For where things live in metadata (fields, structured metadata, eLabFTW settings), see Understanding metadata. SPring-8 BENTEN's metadata (metadata.all.yml) and its schema are described in BENTEN metadata and schema.
Read, write, delete
entry = elab.experiments.entry(101)
md = entry.metadata.structured() # read (None if there is none)
entry.metadata.update_structured({ # write (merged into what is there by default)
"measurement": {"method": {"sub_category": "XAFS"}},
})
entry.metadata.update_structured(md, overwrite=True) # replace
entry.metadata.delete_structured() # delete| Call | Behaviour |
|---|---|
overwrite=False (default) | Merge into the current content; nested dicts are merged, only the given keys change |
overwrite=True | Replace everything with what you pass; keys you leave out disappear |
- Fields (extra_fields) and eLabFTW settings are not touched.
- To load a YAML file, turn it into a dict with
yaml.safe_load()first. - YAML may read dates as datetime objects. The data is stored as JSON, so converting them to strings is safer.
- To write to a locked entry, write inside
with entry.unlocked(): …(8. Lock and timestamp).
Converting to and from a flat "key = value" list
Nested data is hard to put in a table or to point at one value. Flatten it into a list of @ keys: dict levels are joined with @, array elements with .0, .1.
from elabftw_toolkit import benten_schema as bs
md = {"data_info": {"facility": "SPring-8"},
"sample": [{"chemical_formula": "Ag2O"}, {"chemical_formula": "BN"}]}
rows = bs.flatten_at(md)
# [("@data_info@facility", "SPring-8"),
# ("@sample.0@chemical_formula", "Ag2O"),
# ("@sample.1@chemical_formula", "BN")]
bs.unflatten_at(rows) == md # True (back to the nested dict)
bs.unflatten_at(dict(rows)) # also accepts a {key: value} dict- Value types (numbers, strings) are kept, but
Nonebecomes""and does not come back asNone. - You can change one value by its @ key and convert back:
rows = dict(bs.flatten_at(md))
rows["@sample.0@chemical_formula"] = "Ag2CO3"
entry.metadata.update_structured(bs.unflatten_at(rows), overwrite=True)This is the notation of the tables in SPring-8 BENTEN entry bodies (hence the module name benten_schema); it works for any data.
Matching schema paths
A schema (required keys, types, options) writes array elements as [] instead of numbers. path_of() converts an @ key to the schema path.
| Notation | Example | Used in |
|---|---|---|
| @ key | @sample.0@chemical_formula | flat lists, entry body tables |
| schema path | sample[].chemical_formula | schema definitions, path of check results |
| BENTEN Key name | @sample.chemical_formula | BENTEN's schema Excel |
bs.path_of("@sample.0@chemical_formula") # "sample[].chemical_formula"
bs.key_to_path("@sample.chemical_formula") # "sample[].chemical_formula" (from an Excel Key name)
schema = bs.load_schema()
for key, value in bs.flatten_at(md):
item = schema["items"].get(bs.path_of(key)) # the schema definition of that value (None if absent)Checking against a schema
validate() checks structured metadata against a schema and returns the problems.
schema = bs.load_schema() # the bundled BENTEN schema (or a path to your own)
for p in bs.validate(md, schema):
print(p["kind"], p["path"], p["value"], p["detail"])| Kind | Meaning |
|---|---|
unknown | Key not in the schema |
local | Not in the schema but under the top-level local: (facility-specific; allowed) |
required | Required item missing; inside arrays, checked per existing element |
type | Wrong type (number, integer, date, string; a nested dict where a value is expected is also a type problem) |
enum | Value not among the options |
array | Should be a list but is not, or the reverse |
Using your own schema
Prepare the schema as JSON or Excel. The smallest JSON looks like this (the keys of items are schema paths):
{
"source": "my_schema_v1",
"items": {
"measurement.method.sub_category": {"key": "@measurement@method@sub_category", "option": "required",
"type": "keyword", "enum": ["XAFS", "HAXPES"]},
"measurement.date.start_time": {"key": "@measurement@date@start_time", "option": "optional",
"type": "date", "enum": []},
"sample": {"key": "@sample", "option": "optional", "type": "array", "enum": []},
"sample[].chemical_formula": {"key": "@sample.chemical_formula", "option": "required",
"type": "keyword", "enum": []}
}
}| Field | Values |
|---|---|
option | required, optional, automatic |
type | keyword, text (strings), double (number), integer, long (integers), date (2026-12-02 or 2026-12-02 10:30:00), array |
enum | Allowed values (empty: anything) |
For Excel, use the same layout as the BENTEN schema (sheets and columns in BENTEN metadata and schema).
schema = bs.load_schema("my_schema_v1.json") # .xlsx also works (needs openpyxl)
bs.to_json_schema(schema) # a JSON Schema for editors such as VS Code (command: export-jsonschema)To check YAML while you write it in VS Code, see BENTEN metadata and schema (works the same with your own schema).
Checking many files
To check YAML files such as metadata.all.yml folder by folder, use the command line (needs PyYAML: pip install 'elabftw-toolkit[benten]'):
python -m elabftw_toolkit.benten_schema check <folder or .yml> [--schema my_schema_v1.json] [--json result.json] [--xlsx result.xlsx]It summarizes problems by kind and item, with the number of files and example values. --xlsx writes the results to Excel (see the example in BENTEN metadata and schema).
From AI assistants (MCP)
The MCP server (16. MCP server) has matching tools:
| Tool | What it does |
|---|---|
get_structured_metadata | Returns both the nested JSON and the list of @ keys |
validate_structured_metadata | Checks an entry's (or a not-yet-written dict's) structured metadata against a schema |
set_structured_metadata | Writes it (merge by default, overwrite=true replaces) |
You can ask, for example: "Check this YAML against the schema, and if it is fine, put it into measurement 101."
What to read next
- BENTEN metadata and schema: a real example, key notations, the BENTEN schema
- Understanding metadata: fields versus structured metadata
- 15. Validation and plans: checking fields (extra_fields) against a schema