-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
225 lines (209 loc) · 8.51 KB
/
lib.rs
File metadata and controls
225 lines (209 loc) · 8.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// Copyright (c) 2024-2025, DeciSym, LLC
// Licensed under either of:
// - Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// - BSD 3-Clause License (https://opensource.org/licenses/BSD-3-Clause)
// at your option.
//! # JSON2RDF Converter Library
//!
//! This library provides functionality for converting JSON data into RDF format.
//! It uses `serde_json` for JSON parsing and `oxrdf` to build and manage RDF graphs.
//!
//! ## Overview
//! - Converts JSON data structures into RDF triples, generating a graph representation.
//! - Supports blank nodes for nested structures and maps JSON properties to RDF predicates.
//!
//! ## Features
//! - Handles JSON Objects, Arrays, Booleans, Numbers, and Strings as RDF triples.
//! - Allows specifying a custom RDF namespace for generated predicates and objects.
//! - Outputs the RDF data to a specified file or prints it to the console.
use clap::Error;
use oxrdf::vocab::xsd;
use oxrdf::{BlankNode, Graph, Literal, NamedNodeRef, TripleRef};
use serde_json::{Deserializer, Value};
use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Write};
/// Converts JSON data to RDF format.
///
/// This function reads JSON data from the specified file, processes it into RDF triples,
/// and outputs the RDF graph. Users can specify a namespace to use for RDF predicates and
/// an output file for saving the generated RDF data.
///
/// # Arguments
/// - `file_path`: Path to the JSON file.
/// - `namespace`: Optional custom namespace for RDF predicates.
/// - `output_file`: Optional output file path for writing RDF data.
///
/// # Example
/// ```rust
/// use json2rdf::json_to_rdf;
///
/// json_to_rdf(&"tests/airplane.json".to_string(), &Some("http://example.com/ns#".to_string()), &Some("output.nt".to_string()));
/// ```
pub fn json_to_rdf(
file_path: &String,
namespace: &Option<String>,
output_file: &Option<String>,
) -> Result<Option<Graph>, Error> {
let rdf_namespace: String = if namespace.is_some() {
namespace.clone().unwrap()
} else {
"https://decisym.ai/json2rdf/model".to_owned()
};
let file = File::open(file_path).unwrap();
let reader = BufReader::new(file);
let stream = Deserializer::from_reader(reader).into_iter::<Value>();
let mut graph = Graph::default(); // oxrdf Graph object
let mut subject_stack: VecDeque<BlankNode> = VecDeque::new();
let mut property: Option<String> = None;
for value in stream {
match value {
Ok(Value::Object(obj)) => {
let subject = BlankNode::default(); // Create a new blank node
subject_stack.push_back(subject.clone());
for (key, val) in obj {
property = Some(format!("{}/{}", rdf_namespace, key));
process_value(
&mut subject_stack,
&property,
val,
&mut graph,
&rdf_namespace,
);
}
subject_stack.pop_back();
}
Ok(Value::Array(arr)) => {
for val in arr {
process_value(
&mut subject_stack,
&property,
val,
&mut graph,
&rdf_namespace.clone(),
);
}
}
Ok(other) => {
process_value(
&mut subject_stack,
&property,
other,
&mut graph,
&rdf_namespace.clone(),
);
}
Err(e) => {
eprintln!("Error parsing JSON: {}", e);
}
}
}
if let Some(output_path) = output_file {
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(output_path)
.expect("Error opening file");
writeln!(file, "{}", graph).expect("Error writing json2rdf data to file");
Ok(None)
} else {
Ok(Some(graph))
}
}
/// This function handles different JSON data types, converting each into RDF triples:
/// - JSON Objects create new blank nodes and recursively process nested values.
/// - JSON Arrays iterate over each element and process it as an individual value.
/// - JSON Booleans, Numbers, and Strings are converted to RDF literals.
///
/// # Recursion for Nested Structures
/// Recursion is used to handle deeply nested JSON structures, which may contain multiple
/// levels of objects or arrays. This recursive approach allows the function to "dive" into
/// each nested layer of a JSON structure, creating blank nodes for sub-objects and handling
/// them as new subjects within the RDF graph. As a result, each level of JSON data is
/// systematically transformed into RDF triples, regardless of complexity or depth.
///
/// # Arguments
/// - `subject_stack`: Stack of blank nodes representing subjects. Each nested level pushes a new subject to the stack.
/// - `property`: RDF predicate (property) associated with the JSON value.
/// - `value`: JSON value to process.
/// - `graph`: RDF graph where triples are added.
/// - `namespace`: Namespace for generating predicate URIs.
///
/// # JSON Type to RDF Conversion
/// - **Object**: Creates a blank node and recursively processes key-value pairs.
/// - **Array**: Iterates over elements and processes each as a separate value.
/// - **String**: Converts to `xsd:string` literal.
/// - **Boolean**: Converts to `xsd:boolean` literal.
/// - **Number**: Converts to `xsd:int` or `xsd:float` literal based on value type.
fn process_value(
subject_stack: &mut VecDeque<BlankNode>,
property: &Option<String>,
value: Value,
graph: &mut Graph,
namespace: &String,
) {
let ns = if namespace.ends_with("/") {
namespace
} else {
&([namespace, "/"].join(""))
};
if let Some(last_subject) = subject_stack.clone().back() {
if let Some(prop) = property {
match value {
Value::Bool(b) => {
graph.insert(TripleRef::new(
subject_stack.back().unwrap(),
NamedNodeRef::new(prop.as_str()).unwrap(),
&Literal::new_typed_literal(b.to_string(), xsd::BOOLEAN),
));
}
Value::Number(num) => {
if num.as_i64().is_some() {
graph.insert(TripleRef::new(
subject_stack.back().unwrap(),
NamedNodeRef::new(prop.as_str()).unwrap(),
&Literal::new_typed_literal(num.to_string(), xsd::INT),
));
} else if num.as_f64().is_some() {
graph.insert(TripleRef::new(
subject_stack.back().unwrap(),
NamedNodeRef::new(prop.as_str()).unwrap(),
&Literal::new_typed_literal(num.to_string(), xsd::FLOAT),
));
} else {
return;
}
}
Value::String(s) => {
graph.insert(TripleRef::new(
subject_stack.back().unwrap(),
NamedNodeRef::new(prop.as_str()).unwrap(),
&Literal::new_typed_literal(s, xsd::STRING),
));
}
Value::Null => {
//println!("Null value");
}
Value::Object(obj) => {
let subject = BlankNode::default();
subject_stack.push_back(subject);
graph.insert(TripleRef::new(
last_subject,
NamedNodeRef::new(prop.as_str()).unwrap(),
subject_stack.back().unwrap(),
));
for (key, val) in obj {
let nested_property: Option<String> = Some(format!("{}{}", ns, key));
process_value(subject_stack, &nested_property, val, graph, ns);
}
subject_stack.pop_back();
}
Value::Array(arr) => {
for val in arr {
process_value(subject_stack, property, val, graph, ns);
}
}
}
}
}
}