frogcat / ttl2jsonld

Turtle to JSON-LD converter for node.js and browser, no library dependencies.
MIT License
30 stars 7 forks source link

@id value must be an absolut IRI #4

Closed bourgeoa closed 1 year ago

bourgeoa commented 1 year ago

I encountered this issue when implementing ttl2jsonld to serialize jsonld in https://github.com/linkeddata/rdflib.js (see screens below) Your app does a good job to create a compact jsonld output with relative links from a compact ttl. rdflib produce compact ttl with relative links and collections @list.

Actually the only issue is when ttl contains @prefix with non abolute IRI, like @prefix : <#>. or @prefix n: </#>. @id value accepts relative url without any problem.

I made a simple function to find non valid IRI in @context. Then rebuild any @id value and delete @context declaration. A better solution would to make a PR.

  statementsToJsonld (sts) {
    // ttl2jsonld creates context keys for all ttl prefix
    // context keys must be full IRI
    function findId (itemObj) {
      if (itemObj['@id']) {
        const item = itemObj['@id'].split(':')
        if (keys[item[0]]) itemObj['@id'] = jsonldObj['@context'][item[0]] + item[1]
      }
      const itemValues = Object.values(itemObj)
      for (const i in itemValues) {
        if (typeof itemValues[i] !== 'string') { // @list contains array
          findId(itemValues[i])
        }
      }
    }

    const turtleDoc = this.statementsToN3(sts)
    const jsonldObj = ttl2jsonld.parse(turtleDoc)
    const context = jsonldObj['@context']
    const iri = /^[a-z](.*?):(.+?)/g // begin with a letter, contain : followed by at least one character
    const keys = Object.keys(context).filter(key => !context[key].match(iri))

    findId(jsonldObj)
    keys.map(key => { delete jsonldObj['@context'][key] })
    console.log(JSON.stringify(jsonldObj, null, 2))

    return JSON.stringify(jsonldObj, null, 2)
  }

image

image

frogcat commented 1 year ago

I am so sorry for not replying to you sooner.

I understood the problem and added new test case test-issue-4 . Currently, ttl2jsonld.js has been improved to pass test-issue-4.

Please try demo again. And let me know if new test case is not suitable.

bourgeoa commented 1 year ago

Thanks issue resolved.

In test-issue-4 I would have also added a line @prefix : <#>. The demo results are OK.

Waiting for the npm version.

frogcat commented 1 year ago

Thank you again, Version 0.0.9 released.