json_ld_serialization/
lib.rs

1//! This crate implements JSON-LD serialization (from RDF dataset to JSON-LD)
2//! through the [`linked_data`](https://github.com/spruceid/linked-data-rs)
3//! crate.
4//! The input value can be an RDF dataset, or any type implementing
5//! [`linked_data::LinkedData`].
6use std::hash::Hash;
7
8use json_ld_core::{ExpandedDocument, Node, Object};
9
10use linked_data::{rdf_types::Vocabulary, LinkedData, LinkedDataResource, LinkedDataSubject};
11use rdf_types::{
12	interpretation::{
13		ReverseBlankIdInterpretation, ReverseIriInterpretation, ReverseLiteralInterpretation,
14	},
15	vocabulary::IriVocabularyMut,
16	Interpretation,
17};
18
19mod expanded;
20
21use expanded::SerializeExpandedDocument;
22
23pub use expanded::{serialize_node_with, serialize_object_with};
24
25#[derive(Debug, thiserror::Error)]
26pub enum Error {
27	#[error("invalid graph label")]
28	InvalidGraph,
29
30	#[error("invalid predicate")]
31	InvalidPredicate,
32
33	#[error("invalid node object")]
34	InvalidNode,
35
36	#[error("reverse properties on lists are not supported")]
37	ListReverseProperty,
38
39	#[error("included nodes on lists are not supported")]
40	ListInclude,
41}
42
43/// Serialize the given Linked-Data value into a JSON-LD document.
44pub fn serialize(value: &impl LinkedData) -> Result<ExpandedDocument, Error> {
45	serialize_with(&mut (), &mut (), value)
46}
47
48/// Serialize the given Linked-Data value into a JSON-LD document using a
49/// custom vocabulary and interpretation.
50pub fn serialize_with<V, I>(
51	vocabulary: &mut V,
52	interpretation: &mut I,
53	value: &impl LinkedData<I, V>,
54) -> Result<ExpandedDocument<V::Iri, V::BlankId>, Error>
55where
56	V: Vocabulary + IriVocabularyMut,
57	V::Iri: Clone + Eq + Hash,
58	V::BlankId: Clone + Eq + Hash,
59	I: Interpretation
60		+ ReverseIriInterpretation<Iri = V::Iri>
61		+ ReverseBlankIdInterpretation<BlankId = V::BlankId>
62		+ ReverseLiteralInterpretation<Literal = V::Literal>,
63{
64	let serializer = SerializeExpandedDocument::new(vocabulary, interpretation);
65
66	value.visit(serializer)
67}
68
69/// Serialize the given Linked-Data value into a JSON-LD object.
70pub fn serialize_object(
71	value: &(impl LinkedDataSubject + LinkedDataResource),
72) -> Result<Object, Error> {
73	serialize_object_with(&mut (), &mut (), value)
74}
75
76/// Serialize the given Linked-Data value into a JSON-LD node object.
77pub fn serialize_node(
78	value: &(impl LinkedDataSubject + LinkedDataResource),
79) -> Result<Node, Error> {
80	serialize_node_with(&mut (), &mut (), value)
81}