in python/moz/l10n/formats/mf2/from_json.py [0:0]
def mf2_from_json(json: dict[str, Any]) -> Message:
"""
Marshal a MessageFormat 2 data model [JSON Schema](https://github.com/unicode-org/message-format-wg/blob/main/spec/data-model/message.json)
object into a parsed `moz.l10n.message.data.Message`.
May raise `MF2ValidationError`.
"""
try:
msg_type = json["type"]
if msg_type not in {"message", "select"}:
raise MF2ValidationError(f"Invalid JSON message: {json}")
declarations: dict[str, Expression] = {}
for decl in json["declarations"]:
decl_type = decl["type"]
if decl_type not in {"input", "local"}:
raise MF2ValidationError(f"Invalid JSON declaration type: {decl}")
decl_name = _string(decl, "name")
decl_expr = _expression(decl["value"])
if decl_type == "input":
if (
not isinstance(decl_expr.arg, VariableRef)
or decl_expr.arg.name != decl_name
):
raise MF2ValidationError(f"Invalid JSON .input declaration: {decl}")
if decl_name in declarations:
raise MF2ValidationError(f"Duplicate JSON declaration for ${decl_name}")
declarations[decl_name] = decl_expr
if msg_type == "message":
pattern = _pattern(json["pattern"])
return PatternMessage(pattern, declarations)
assert msg_type == "select"
selectors = tuple(_variable(sel) for sel in json["selectors"])
variants = {
tuple(_key(key) for key in vari["keys"]): _pattern(vari["value"])
for vari in json["variants"]
}
return SelectMessage(declarations, selectors, variants)
except (IndexError, KeyError, TypeError) as err:
raise MF2ValidationError(f"Invalid JSON: {err!r}")