From e72efd9c4da565decf249cc167360d38580d70e4 Mon Sep 17 00:00:00 2001 From: Charles Tapley Hoyt Date: Fri, 28 Jul 2023 15:56:52 -0400 Subject: [PATCH] Improve JSON-LD context parsing (#61) Following https://github.com/w3c/json-ld-syntax/issues/329 and https://github.com/w3c/json-ld-syntax/issues/329, this PR updates the processing of JSON-LD contexts to handle when there are dictionaries. --- src/curies/api.py | 8 +++++++- tests/test_api.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/curies/api.py b/src/curies/api.py index 4970757..9952c64 100644 --- a/src/curies/api.py +++ b/src/curies/api.py @@ -624,7 +624,13 @@ def from_jsonld(cls, data: LocationOr[Dict[str, Any]]) -> "Converter": >>> converter = Converter.from_jsonld(url) >>> "rdf" in converter.prefix_map """ - return cls.from_prefix_map(_prepare(data)["@context"]) + prefix_map = {} + for key, value in _prepare(data)["@context"].items(): + if isinstance(value, str): + prefix_map[key] = value + elif isinstance(value, dict) and value.get("@prefix") is True: + prefix_map[key] = value["@id"] + return cls.from_prefix_map(prefix_map) @classmethod def from_jsonld_github( diff --git a/tests/test_api.py b/tests/test_api.py index 9ad8e2c..ee80bda 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -145,6 +145,24 @@ def test_bioregistry(self): self.assertIn("chebi", c.prefix_map) self.assertNotIn("CHEBI", c.prefix_map) + def test_jsonld(self): + """Test parsing JSON-LD context.""" + context = { + "@context": { + "hello": "https://example.org/hello:", + "CHEBI": { + "@prefix": True, + "@id": "http://purl.obolibrary.org/CHEBI_", + }, + "nope": { + "nope": "nope", + }, + }, + } + converter = Converter.from_jsonld(context) + self.assertIn("hello", converter.prefix_map) + self.assertIn("CHEBI", converter.prefix_map) + def test_from_github(self): """Test getting a JSON-LD map from GitHub.""" with self.assertRaises(ValueError):