From 32c2fb3bbc4d3b6629b21a9dfea6c1d6dbfe90b1 Mon Sep 17 00:00:00 2001 From: Greenscreener Date: Wed, 20 Sep 2023 20:13:38 +0200 Subject: [PATCH] =?UTF-8?q?P=C5=99id=C3=A1n=20import=20jsonu=20do=20metada?= =?UTF-8?q?t,=20resolves=20#36.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/formatitko/context.py | 8 ++++++++ src/formatitko/transform_processor.py | 5 +++++ test/test.json | 22 ++++++++++++++++++++++ test/test.md | 6 ++++++ 4 files changed, 41 insertions(+) create mode 100644 test/test.json diff --git a/src/formatitko/context.py b/src/formatitko/context.py index ecde7f2..ac13b7e 100644 --- a/src/formatitko/context.py +++ b/src/formatitko/context.py @@ -101,6 +101,14 @@ class Context: for k in keys[:-1]: meta = meta[k] del meta.content[key[-1]] # A hack because MetaMap doesn't have a __delitem__ + + def import_metadata(self, data, key: str=""): + if isinstance(data, dict) and isinstance(self.get_metadata(key), dict): + for subkey, value in enumerate(data): + self.import_metadata(value, key+"."+subkey if key != "" else subkey) + else: + self.set_metadata(key, data) + # This is a custom element which creates \begingroup \endgroup groups in TeX diff --git a/src/formatitko/transform_processor.py b/src/formatitko/transform_processor.py index bd98656..c8db234 100644 --- a/src/formatitko/transform_processor.py +++ b/src/formatitko/transform_processor.py @@ -10,6 +10,7 @@ import os import re import warnings import importlib +import json from .whitespace import NBSP from .elements import FQuoted @@ -469,6 +470,10 @@ class TransformProcessor: module = importlib.import_module(matches.group(1)) module_name = matches.group(1) if matches.group(2) is None else matches.group(2) self.context.add_commands_from_module(module, module_name) + elif e.attributes["type"] == "metadata": + data = json.load(open(self.context.dir + "/" + e.content[0].text[1:], "r")) + key = "" if not "key" in e.attributes else e.attributes["key"] + self.context.import_metadata(data, key) else: raise SyntaxError(f"`{e.attributes['type']}`: invalid import type") diff --git a/test/test.json b/test/test.json new file mode 100644 index 0000000..75417f0 --- /dev/null +++ b/test/test.json @@ -0,0 +1,22 @@ +[ + { + "first_name": "Jan", + "last_name": "Černohorský", + "abbrev": "GS", + "gender": "M", + "contacts_public": { + "homepage": "https://grsc.cz" + } + }, + { + "first_name": "Ondřej", + "last_name": "Machota", + "domestic_name": "Ondra", + "abbrev": "OM", + "gender": "M", + "contacts_public": { + "email": "ondrejmachota@gmail.com", + "discord": "ondrejmachota#0196" + } + } +] diff --git a/test/test.md b/test/test.md index 5c62835..4de4cf3 100644 --- a/test/test.md +++ b/test/test.md @@ -11,6 +11,12 @@ lang: "en" [#test-files/test-import.md]{type=md} +[#test.json]{type=metadata key=orgs} + +```python {.run} +return parse_string(f"Hello, {context.get_metadata('orgs')[0]['first_name']}!") +``` + # Hello world! ## H2 ### H3