Skip to content

Commit aa16188

Browse files
committed
Added additional documentation for Rust Docs. Returns either a graph or a file with triples
1 parent 28def87 commit aa16188

4 files changed

Lines changed: 139 additions & 52 deletions

File tree

airplane.json

Lines changed: 0 additions & 35 deletions
This file was deleted.

src/lib.rs

Lines changed: 78 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
//! # JSON2RDF Converter Library
2+
//!
3+
//! This library provides functionality for converting JSON data into RDF format.
4+
//! It uses `serde_json` for JSON parsing and `oxrdf` to build and manage RDF graphs.
5+
//!
6+
//! ## Overview
7+
//! - Converts JSON data structures into RDF triples, generating a graph representation.
8+
//! - Supports blank nodes for nested structures and maps JSON properties to RDF predicates.
9+
//!
10+
//! ## Features
11+
//! - Handles JSON Objects, Arrays, Booleans, Numbers, and Strings as RDF triples.
12+
//! - Allows specifying a custom RDF namespace for generated predicates and objects.
13+
//! - Outputs the RDF data to a specified file or prints it to the console.
14+
115
use oxrdf::vocab::xsd;
216
use oxrdf::{BlankNode, Graph, Literal, NamedNodeRef, TripleRef};
317

@@ -6,7 +20,34 @@ use std::collections::VecDeque;
620
use std::fs::File;
721
use std::io::{BufReader, Write};
822

9-
pub fn json_to_rdf(file_path: &String, namespace: &Option<String>, output_file: &Option<String>) {
23+
pub enum GraphOrMessage {
24+
Graph(Graph),
25+
Message(String),
26+
}
27+
28+
/// Converts JSON data to RDF format.
29+
///
30+
/// This function reads JSON data from the specified file, processes it into RDF triples,
31+
/// and outputs the RDF graph. Users can specify a namespace to use for RDF predicates and
32+
/// an output file for saving the generated RDF data.
33+
///
34+
/// # Arguments
35+
/// - `file_path`: Path to the JSON file.
36+
/// - `namespace`: Optional custom namespace for RDF predicates.
37+
/// - `output_file`: Optional output file path for writing RDF data.
38+
///
39+
/// # Example
40+
/// ```rust
41+
/// use json2rdf::json_to_rdf;
42+
///
43+
/// json_to_rdf(&"test/airplane.json".to_string(), &Some("http://example.com/ns#".to_string()), &Some("output.nt".to_string()));
44+
/// ```
45+
46+
pub fn json_to_rdf(
47+
file_path: &String,
48+
namespace: &Option<String>,
49+
output_file: &Option<String>,
50+
) -> Result<GraphOrMessage, String> {
1051
let rdf_namespace: String = if namespace.is_some() {
1152
namespace.clone().unwrap()
1253
} else {
@@ -67,13 +108,44 @@ pub fn json_to_rdf(file_path: &String, namespace: &Option<String>, output_file:
67108
}
68109
}
69110

70-
let mut buffer: Vec<u8> = Vec::new();
71-
writeln!(buffer, "{}", graph.to_string()).unwrap();
72-
73-
let file = File::create("foo.txt");
74-
writeln!(file.unwrap(), "{}", String::from_utf8_lossy(&buffer)).unwrap();
111+
if let Some(output_path) = output_file {
112+
let mut file = File::create(output_path).expect("Error creating file");
113+
writeln!(file, "{}", graph).expect("Error writing to file");
114+
Ok(GraphOrMessage::Message(format!(
115+
"RDF created at: {}",
116+
output_path
117+
)))
118+
} else {
119+
Ok(GraphOrMessage::Graph(graph))
120+
}
75121
}
76122

123+
/// This function handles different JSON data types, converting each into RDF triples:
124+
/// - JSON Objects create new blank nodes and recursively process nested values.
125+
/// - JSON Arrays iterate over each element and process it as an individual value.
126+
/// - JSON Booleans, Numbers, and Strings are converted to RDF literals.
127+
///
128+
/// # Recursion for Nested Structures
129+
/// Recursion is used to handle deeply nested JSON structures, which may contain multiple
130+
/// levels of objects or arrays. This recursive approach allows the function to "dive" into
131+
/// each nested layer of a JSON structure, creating blank nodes for sub-objects and handling
132+
/// them as new subjects within the RDF graph. As a result, each level of JSON data is
133+
/// systematically transformed into RDF triples, regardless of complexity or depth.
134+
///
135+
/// # Arguments
136+
/// - `subject_stack`: Stack of blank nodes representing subjects. Each nested level pushes a new subject to the stack.
137+
/// - `property`: RDF predicate (property) associated with the JSON value.
138+
/// - `value`: JSON value to process.
139+
/// - `graph`: RDF graph where triples are added.
140+
/// - `namespace`: Namespace for generating predicate URIs.
141+
///
142+
/// # JSON Type to RDF Conversion
143+
/// - **Object**: Creates a blank node and recursively processes key-value pairs.
144+
/// - **Array**: Iterates over elements and processes each as a separate value.
145+
/// - **String**: Converts to `xsd:string` literal.
146+
/// - **Boolean**: Converts to `xsd:boolean` literal.
147+
/// - **Number**: Converts to `xsd:int` or `xsd:float` literal based on value type.
148+
77149
fn process_value(
78150
subject_stack: &mut VecDeque<BlankNode>,
79151
property: &Option<String>,

src/main.rs

Lines changed: 60 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,91 @@
1+
//! # JSON2RDF Converter
2+
//!
3+
//! This is a Rust-based tool that converts JSON data into RDF format. It uses the `serde_json` crate
4+
//! for JSON parsing and the `oxrdf` crate to construct RDF graphs.
5+
//!
6+
//! ## Features
7+
//! - Parses JSON input and converts it to RDF triples
8+
//! - Supports specifying a custom namespace for generated RDF nodes
9+
//! - Outputs RDF data to a specified file
10+
//!
11+
//! ## Usage
12+
//! Run the JSON2RDF converter from the command line. For detailed usage information, run:
13+
//! ```
14+
//! json2rdf --help
15+
//! ```
16+
//!
17+
//! ## Example
18+
//! To convert a JSON file to RDF format with a specified namespace and output file:
19+
//! ```
20+
//! json2rdf convert --namespace http://example.com/ns# --json-files data.json --output-file output.nt
21+
//! ```
22+
//! This will take `data.json`, apply the specified namespace, and save the RDF output in `output.nt`.
123
use clap::{Parser, Subcommand};
224
mod lib;
3-
/// JSON2RDF Converter
4-
/// This tool converts JSON data into RDF format.
25+
26+
/// Command-line interface for JSON2RDF Converter
27+
///
28+
/// This struct defines the command-line interface (CLI) for interacting with the JSON2RDF converter.
529
#[derive(Parser)]
6-
#[command(version, about, long_about = None)]
30+
#[command(version, about = "Converts JSON data into RDF format.")]
731
struct Cli {
32+
/// CLI command selection
833
#[command(subcommand)]
934
command: Option<Commands>,
1035
}
1136

37+
/// Supported Commands
38+
///
39+
/// Contains the available commands for the JSON2RDF converter.
1240
#[derive(Subcommand)]
1341
enum Commands {
14-
/// The JSON2RDF CLI
42+
/// Convert JSON to RDF format.
43+
///
44+
/// The `convert` command parses a JSON file, converts it to RDF triples using `serde_json` for parsing
45+
/// and `oxrdf` to construct the graph, and saves the output.
1546
Convert {
16-
/// namespace to be used for graph generation
47+
/// Namespace for RDF graph generation.
48+
///
49+
/// A custom namespace to prefix RDF resources created from JSON keys and values.
1750
#[arg(short, long)]
1851
namespace: Option<String>,
19-
/// path to JSON file(s)
52+
53+
/// Path to input JSON file(s).
54+
///
55+
/// Provide the path to one or more JSON files that will be parsed and converted.
2056
#[arg(short, long)]
2157
json_files: String,
22-
/// write triples from oxrdf graph to a file
58+
59+
/// Path to output file.
60+
///
61+
/// Optional: Specify the path to save the generated RDF data.
2362
#[arg(short, long)]
2463
output_file: Option<String>,
2564
},
2665
}
66+
2767
fn main() {
2868
let cli = Cli::parse();
2969

70+
// Match command and execute corresponding functionality
3071
match &cli.command {
3172
Some(Commands::Convert {
3273
namespace,
3374
json_files,
3475
output_file,
3576
}) => {
36-
if Some(output_file).is_some() {
37-
lib::json_to_rdf(json_files, namespace, output_file);
38-
} else {
39-
lib::json_to_rdf(json_files, namespace, &None);
77+
match lib::json_to_rdf(json_files, namespace, output_file) {
78+
Ok(res) => match res {
79+
lib::GraphOrMessage::Graph(graph) => {
80+
// Handle the case where the function returns a Graph
81+
println!("Graph created with {} triples", graph.len());
82+
}
83+
lib::GraphOrMessage::Message(message) => {
84+
// Handle the case where the function returns a success message
85+
println!("{}", message);
86+
}
87+
},
88+
Err(e) => eprintln!("Error writing: {}", e),
4089
}
4190
}
4291
None => {}

test/intergration_test.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

0 commit comments

Comments
 (0)