Is there a converter between json-ld and turtle(n3)?

https://npm.runkit.com/rdf-translator uses https://bitbucket.org/alexstolz/rdf-translator, but it stops maintaining.

Is there an alternative written in JS?

1 Like

I think https://rdf.js.org/ is a good resource for finding stuff like this in general, but rdflib.js allows you to read JSON-LD and write to Turtle at least (not the other way around though IIRC).

rdflib.js can both read and write JSON-LD. Here’s how:

function turtle2jsonld( turtleString, store, uri ){
  return new Promise(resolve=>{
    $rdf.parse( turtleString, store, uri, "text/turtle", e => {
        if(e) { console.log("Parse Error! "); return resolve(e) }
        $rdf.serialize(null,store, uri,'application/ld+json',(e,s)=>{
            if(e) { console.log("Serialize Error! "); return resolve(e) }
            return resolve(s)
        })
    })
  })
}
function jsonld2turtle( jsonldString, store, uri ){
  return new Promise(resolve=>{
    $rdf.parse( jsonldString, store, uri, "application/ld+json", e => {
        if(e) { console.log("Parse Error! "); return resolve(e) }
        $rdf.serialize(null,store, uri,'text/turtle',(e,s)=>{
            if(e) { console.log("Serialize Error! "); return resolve(e) }
            return resolve(s)
        })
    })
  })
}
7 Likes

Hi @jeffz , seems it is not working, I’ve created a runkit note for it https://github.com/linkeddata/rdflib.js/issues/364#issuecomment-568694710

1 Like

It’s 2024 and I still land on this page when I’m trying to find something to covert .ttl format to json-ld. None of the first page of Google results do the job. Is there something I’m missing in the complexity of this task? :pleading_face:

There’s also jsonld.js (GitHub - digitalbazaar/jsonld.js: A JSON-LD Processor and API implementation in JavaScript) that can perform various operations on jsonld, including conversion into nquads.

1 Like

EasyRdf - Converter works for me.

1 Like

I should also mention that the issue that @linonetwo mentioned above in 2019 was solved a few months later and that the example with rdflib.js I provided above works again.

Hi @pduchesne and @jeffz , thanks for the speedy replies. None of those three (jsonld.js / easyrdf site / rdflib.js code solution) seemed to work converting my .ttl to json-ld, everything errored (although the .ttl was auto-generated by rdflib.js, so should be valid :thinking: ). I’ve decided though for my use case (making json-ld) it’s probably better to just generate json-ld manually with code, rather than reading the data into an rdflib.js graph and trying to get json-ld out of it somehow. That way I can have more control over the structure. But I hope someone finds these refreshed answers and it helps them! May be back with more q’s…