Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rdflib.js, how to serialize the data into turtle (.ttl) format?

How can I serialize RDF in turtle using rdflib.js? There's not much documentation. I can use:

Serializer.statementsToN3(destination);

to serialize into the N3 format, but not much besides that. I've tried altering the aforementioned command to stuff like statementsToTtl/Turtle/TURTLE/TTL, but nothing seems to work.

like image 976
Fox Avatar asked Jan 23 '26 16:01

Fox


1 Answers

Figured it out. Courtesy of this (secret) Github gist.

$rdf.serialize(undefined, source, undefined,` 'text/turtle', function(err, str){
// do whatever you want, the data is in the str variable.
})

This is the code from the aforementioned Github gist.

/**
* rdflib.js with node.js -- basic RDF API example.
* @author ckristo
*/

var fs = require('fs');
var $rdf = require('rdflib');

FOAF = $rdf.Namespace('http://xmlns.com/foaf/0.1/');
XSD  = $rdf.Namespace('http://www.w3.org/2001/XMLSchema#');

// - create an empty store
var kb = new $rdf.IndexedFormula();

// - load RDF file
fs.readFile('foaf.rdf', function (err, data) {
if (err) { /* error handling */ }

// NOTE: to get rdflib.js' RDF/XML parser to work with node.js,
// see https://github.com/linkeddata/rdflib.js/issues/47

// - parse RDF/XML file
$rdf.parse(data.toString(), kb, 'foaf.rdf', 'application/rdf+xml', function(err, kb) {
    if (err) { /* error handling */ }

    var me = kb.sym('http://kindl.io/christoph/foaf.rdf#me');

    // - add new properties
    kb.add(me, FOAF('mbox'), kb.sym('mailto:[email protected]'));
    kb.add(me, FOAF('nick'), 'ckristo');

    // - alter existing statement
    kb.removeMany(me, FOAF('age'));
    kb.add(me, FOAF('age'), kb.literal(25, null, XSD('integer')));

    // - find some existing statements and iterate over them
    var statements = kb.statementsMatching(me, FOAF('mbox'));
    statements.forEach(function(statement) {
        console.log(statement.object.uri);
    });

    // - delete some statements
    kb.removeMany(me, FOAF('mbox'));

    // - print modified RDF document
    $rdf.serialize(undefined, kb, undefined, 'application/rdf+xml', function(err, str) {
        console.log(str);
    });
});
});
like image 67
Fox Avatar answered Jan 25 '26 07:01

Fox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!