Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

feat(graph): read and write JSON-LD like any other serialisation

Fabio Rovai3449c6d16481
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 50bbbacb..530054cb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,22 @@ All notable changes to Open Ontologies are documented here.
## [Unreleased]
### Fixed
+- **JSON-LD is read and written like any other serialisation.** `oxrdfio` has
+ supported it all along, but the engine's format handling did not: `parse_format`
+ had no JSON-LD arm, and `detect_format` fell back to Turtle for any extension it
+ did not recognise, so a `.jsonld` document was handed to the Turtle parser and
+ died on `{ is not a valid predicate` — an error that names the wrong problem and
+ sends you looking at a file that was never broken. `.jsonld` and `.json` now map
+ to JSON-LD, `parse_format` accepts `jsonld`, `json-ld` and `json` (`json-ld` is
+ the W3C media-type spelling and what most other tooling takes, so rejecting it
+ turned a correct format name into an error), and the body sniffer recognises a
+ JSON-LD document published under a misleading extension. The sniff requires an
+ opening `{` or `[` *and* a `"@context"`, `"@id"` or `"@graph"` keyword: a bare
+ brace proves nothing, since TriG opens its default graph block with `{` and
+ Turtle admits `[` as a blank-node subject. `tests/graph_jsonld_test.rs`.
+ The Python package had the mirror defect, accepting `jsonld` while rejecting
+ `json-ld`; both spellings and `json` now resolve.
+
- **The compile cache no longer flattens named graphs** (issue #112). It was
written as N-Triples, a format that cannot carry a graph name, so the cached
artefact was not equivalent to the source it stood for: a dataset went in and
diff --git a/python/src/open_ontologies_lite/engine.py b/python/src/open_ontologies_lite/engine.py
index 15bcb6d3..938a650b 100644
--- a/python/src/open_ontologies_lite/engine.py
+++ b/python/src/open_ontologies_lite/engine.py
@@ -27,6 +27,10 @@ _FORMATS = {
"xml": ox.RdfFormat.RDF_XML,
"n3": ox.RdfFormat.N3,
"jsonld": ox.RdfFormat.JSON_LD,
+ # The W3C media-type registration and most other tooling, rdflib included,
+ # spell it with the hyphen. Taking only "jsonld" rejected a correct name.
+ "json-ld": ox.RdfFormat.JSON_LD,
+ "json": ox.RdfFormat.JSON_LD,
}
OWL_CLASS = "http://www.w3.org/2002/07/owl#Class"
diff --git a/python/tests/test_engine.py b/python/tests/test_engine.py
index 52153ddf..641bd8b6 100644
--- a/python/tests/test_engine.py
+++ b/python/tests/test_engine.py
@@ -80,3 +80,25 @@ def test_diff():
b = "<http://x/A> <http://x/p> <http://x/C> ."
d = OntologyEngine.diff(a, b, "ntriples")
assert d["added_count"] == 1 and d["removed_count"] == 1
+
+
+def test_json_ld_spelling_is_accepted():
+ """"json-ld" is the W3C media-type spelling and what rdflib itself takes.
+
+ Accepting only "jsonld" turns a correct format name into a ValueError, and
+ the error message did not even hint that the hyphenless spelling was the
+ one on offer.
+ """
+ from open_ontologies_lite import resolve_format
+
+ assert resolve_format("json-ld") is resolve_format("jsonld")
+
+
+def test_json_ld_spelling_round_trips_through_the_engine():
+ from open_ontologies_lite import OntologyEngine
+
+ ttl = "@prefix ex: <http://example.org/> . ex:Alice a ex:Person ."
+ engine = OntologyEngine()
+ engine.load(ttl, "turtle")
+ doc = engine.convert(ttl, "turtle", "json-ld")
+ assert OntologyEngine.validate(doc, "json-ld").ok
diff --git a/src/graph.rs b/src/graph.rs
index f4488ebf..758404bb 100644
--- a/src/graph.rs
+++ b/src/graph.rs
@@ -2,7 +2,7 @@ use std::io::Cursor;
use std::path::Path;
use std::sync::Mutex;
-use oxigraph::io::{RdfFormat, RdfParser, RdfSerializer};
+use oxigraph::io::{JsonLdProfileSet, RdfFormat, RdfParser, RdfSerializer};
use oxigraph::model::*;
use oxigraph::sparql::{QueryResults, SparqlEvaluator};
use oxigraph::store::Store;
@@ -540,6 +540,10 @@ impl GraphStore {
RdfFormat::NQuads
} else if path.ends_with(".trig") {
RdfFormat::TriG
+ } else if path.ends_with(".jsonld") || path.ends_with(".json") {
+ RdfFormat::JsonLd {
+ profile: JsonLdProfileSet::empty(),
+ }
} else {
RdfFormat::Turtle
}
@@ -577,6 +581,22 @@ impl GraphStore {
return RdfFormat::Turtle;
}
+ // A JSON body is proof of JSON-LD in a way `{` alone is not: TriG also
+ // opens its default graph block with `{`, and Turtle admits `[` as a
+ // blank-node subject. Requiring a JSON-LD keyword alongside the opening
+ // brace keeps those two out while still rescuing the common case of a
+ // JSON-LD document published under `.owl`, `.rdf` or no extension at
+ // all, which would otherwise reach the Turtle parser and die there.
+ let opens_json = head.starts_with('{') || head.starts_with('[');
+ let has_jsonld_keyword = content.contains("\"@context\"")
+ || content.contains("\"@id\"")
+ || content.contains("\"@graph\"");
+ if opens_json && has_jsonld_keyword {
+ return RdfFormat::JsonLd {
+ profile: JsonLdProfileSet::empty(),
+ };
+ }
+
ext_format
}
@@ -587,8 +607,14 @@ impl GraphStore {
"rdfxml" | "rdf" | "xml" | "owl" => Ok(RdfFormat::RdfXml),
"nquads" | "nq" => Ok(RdfFormat::NQuads),
"trig" => Ok(RdfFormat::TriG),
+ // "json-ld" is the spelling in the W3C media type registration and
+ // in most other tooling, so rejecting it turns a correct format
+ // name into an error.
+ "jsonld" | "json-ld" | "json" => Ok(RdfFormat::JsonLd {
+ profile: JsonLdProfileSet::empty(),
+ }),
_ => anyhow::bail!(
- "Unknown format: {}. Supported: turtle, ntriples, rdfxml, nquads, trig",
+ "Unknown format: {}. Supported: turtle, ntriples, rdfxml, nquads, trig, jsonld",
name
),
}
diff --git a/tests/graph_jsonld_test.rs b/tests/graph_jsonld_test.rs
new file mode 100644
index 00000000..05bf1d44
--- /dev/null
+++ b/tests/graph_jsonld_test.rs
@@ -0,0 +1,115 @@
+//! JSON-LD is a first-class RDF serialisation and the underlying `oxrdfio`
+//! already supports it, but the engine's format handling did not: `.jsonld`
+//! fell through extension detection to Turtle, so a valid JSON-LD document was
+//! handed to the Turtle parser and failed with a misleading syntax error.
+
+use open_ontologies::graph::GraphStore;
+
+const JSONLD_DOC: &str = r#"{
+ "@context": { "ex": "http://example.org/" },
+ "@id": "ex:Alice",
+ "@type": "ex:Person",
+ "ex:name": "Alice"
+}"#;
+
+#[test]
+fn validate_file_reads_a_jsonld_document() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("doc.jsonld");
+ std::fs::write(&path, JSONLD_DOC).unwrap();
+
+ let count = GraphStore::validate_file(path.to_str().unwrap())
+ .expect("a .jsonld file must validate as JSON-LD, not as Turtle");
+ assert_eq!(count, 2);
+}
+
+#[test]
+fn load_file_reads_a_jsonld_document() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("doc.jsonld");
+ std::fs::write(&path, JSONLD_DOC).unwrap();
+
+ let store = GraphStore::new();
+ let loaded = store
+ .load_file(path.to_str().unwrap())
+ .expect("a .jsonld file must load as JSON-LD, not as Turtle");
+ assert_eq!(loaded, 2);
+ assert_eq!(store.triple_count(), 2);
+
+ let results = store
+ .sparql_select("SELECT ?s WHERE { ?s a <http://example.org/Person> }")
+ .unwrap();
+ assert!(results.contains("Alice"));
+}
+
+#[test]
+fn serialize_emits_jsonld() {
+ let store = GraphStore::new();
+ store
+ .load_turtle(
+ r#"@prefix ex: <http://example.org/> .
+ ex:Alice a ex:Person ."#,
+ None,
+ )
+ .unwrap();
+
+ let out = store
+ .serialize("jsonld")
+ .expect("jsonld must be an accepted serialisation format");
+ let head = out.trim_start();
+ assert!(head.starts_with('[') || head.starts_with('{'));
+ assert!(out.contains("http://example.org/Alice"));
+}
+
+#[test]
+fn jsonld_round_trips_through_a_file() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("round.jsonld");
+
+ let source = GraphStore::new();
+ source
+ .load_turtle(
+ r#"@prefix ex: <http://example.org/> .
+ ex:Alice a ex:Person ;
+ ex:name "Alice" ."#,
+ None,
+ )
+ .unwrap();
+ source.save_file(path.to_str().unwrap(), "jsonld").unwrap();
+
+ let reloaded = GraphStore::new();
+ reloaded.load_file(path.to_str().unwrap()).unwrap();
+ assert_eq!(reloaded.triple_count(), source.triple_count());
+}
+
+#[test]
+fn json_ld_spelling_is_accepted_as_a_format_name() {
+ let store = GraphStore::new();
+ store
+ .load_turtle(
+ r#"@prefix ex: <http://example.org/> .
+ ex:Alice a ex:Person ."#,
+ None,
+ )
+ .unwrap();
+
+ // "json-ld" is the spelling used by the W3C media type registration and by
+ // most other tooling, so accepting only "jsonld" turns a correct format
+ // name into an error.
+ assert!(store.serialize("json-ld").is_ok());
+}
+
+#[test]
+fn a_jsonld_body_in_a_misnamed_file_is_still_read_as_jsonld() {
+ // Extension detection is a hint, not proof: `.owl` and `.rdf` are routinely
+ // used for whatever serialisation the publisher happened to emit. The
+ // engine already sniffs the body to rescue Turtle-in-.owl; JSON-LD needs
+ // the same treatment or a misnamed file fails with a parser error.
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("doc.owl");
+ std::fs::write(&path, JSONLD_DOC).unwrap();
+
+ let count = GraphStore::validate_file(path.to_str().unwrap())
+ .expect("a JSON-LD body must be detected from its content");
+ assert_eq!(count, 2);
+}