Fontanka16
Fontanka16

Reputation: 1323

Convert or translate a RDF/XML file to JSON-LD format

I am trying to parse a RDF/XML formatted document into JSON-LD in order to frame it. All using Node.js and not utilizing any web service APIs (a not too uncommon solution).

I feel that I am almost there, but my current approach feels clumsy to say the least. Putting the graph into a rdflib store and then querying it back up again gives me a strange response with some headers and no real context within the graph. Hence the doc[5]['@graph'] stuff in the middle.

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

var path = 'path_to_rdf_file'

const frame = {}

fs.readFile(path, 'utf8', function (err, data) {
    var uri = 'https://some.other.uri'
    var store = $rdf.graph()
    $rdf.parse(data, store, uri, 'application/rdf+xml')
    var a = $rdf.serialize(null, store, uri, 'application/n-quads')
    jsonld.fromRDF(a, { format: 'application/n-quads' }, (err, doc) => {
        jsonld.flatten(doc[5]['@graph'], (err, flattened) => {
            console.log(flattened)
            jsonld.frame(flattened, frame, (err, framed) => {
                resolve(framed)
            })
        })
    })
})

With all the RDF and linked data packages floating around npm, I reckon there must be a simpler solution out there that could get me from A to B.

How could I parse my RDF/XML document into a JSON-LD document without using rdflib this way?

Upvotes: 3

Views: 2463

Answers (1)

Philipp Gfeller
Philipp Gfeller

Reputation: 1259

You can use rdflib to serialize to application/ld+json directly (rdflib uses the jsonld module internally).

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

var path = 'path_to_rdf_file'

const frame = {}

const toJSONLD = (data, uri, mimeType) => {
    return new Promise((resolve, reject) => {
        var store = $rdf.graph()
        $rdf.parse(data, store, uri, mimeType)
        $rdf.serialize(null, store, uri, 'application/ld+json', (err, jsonldData) => {
            if (err) return reject(err);
            resolve(JSON.parse(jsonldData))
        })
    })
}

fs.readFile(path, 'utf8', function (err, data) {
    var uri = 'https://some.other.uri'
    toJSONLD(data, uri, 'application/rdf+xml')
        .then((doc) => {
            jsonld.flatten(doc[5]['@graph'], (err, flattened) => {
                console.log(flattened)
                jsonld.frame(flattened, frame, (err, framed) => {
                    resolve(framed)
                })
            })
        })
})

Another way would be to equip jsonld with custom parsers for your data type using jsonld.regiserRDFParser (https://www.npmjs.com/package/jsonld#custom-rdf-parser). Allthough you would likely use rdflib for this task as well.

Upvotes: 2

Related Questions