JSON-LD Contexts
Useful JSON-LD contexts!

Table of Contents

1 JSON-LD Contexts

1.1 Script

Insprired by https://gist.github.com/niklasl/2770154

import sys
import rdflib
import json
from rdflib import Graph, Namespace, URIRef
from rdflib.namespace import NamespaceManager, XSD, RDF, RDFS, OWL

output = ""

for row in table:

  prefix = str(row[1]).strip()
  url = str(row[2]).strip()
  source = str(row[3]).strip()
  if(source == ''):
    source = url

  g = Graph().parse(source)
  nm = NamespaceManager(g)
  
  # TODO read imports too?
  
  stdObjectRanges = { RDF.Property, RDFS.Class, RDFS.Datatype, OWL.Class, OWL.Thing, OWL.Ontology }
  stdDataRanges = { RDFS.Literal }
  noRanges = { RDFS.Resource }
  
  # collect classes and properties
  classes = set(g.subjects(RDF.type, OWL.Class)) | set(g.subjects(RDF.type, RDFS.Class))
  objectProperties = set(g.subjects(RDF.type, OWL.ObjectProperty))
  dataProperties = set(g.subjects(RDF.type, OWL.DatatypeProperty))
  otherProperties = set(g.subjects(RDF.type, RDF.Property)) | set(g.subjects(RDF.type, OWL.AnnotationProperty))
  
  # decide if other Properties are object or data properties:
  for p in set(g.subjects(RDF.type, RDF.Property)) - (objectProperties | dataProperties):
      if (set(g.objects(p, RDFS.range)) & (classes | stdObjectRanges)) - (stdDataRanges | noRanges):
          objectProperties.add(p)
      elif filter(lambda p : p.startswith(XSD), set(g.objects(p, RDFS.range))) or set(g.objects(p, RDFS.range)) & stdDataRanges:
          dataProperties.add(p)
  
  ####
  
  context = list()
  context.append('"@version": 1.1')
  
  # Prefixes
  prefixes = list(map(lambda p : '"' + p[0] + '": "' + str(p[1]) + '"', sorted(NamespaceManager(g).namespaces())))
  context.extend(prefixes)
  
  # Imports?
  
  # Properties
  properties = list()
  for p in sorted(objectProperties | dataProperties | otherProperties):
      attributes = list()
  
      if p in objectProperties:
          attributes.append('"@type": "@id"')
  
      if p in dataProperties:
          ranges = set(g.objects(p, RDFS.range)) - { RDFS.Literal }
          xsdranges = set(filter(lambda p : p.startswith(XSD), ranges))
          if len(ranges) == len(xsdranges) == 1:
              attributes.append('"@type": "%s"' % (nm.qname(xsdranges.pop())))
  
      if (p, RDFS.range, RDF.List) in g:
          attributes.append('"@container": "@list"')
  
      properties.append('"' + nm.qname(p) + '": {' + ', '.join(attributes) + '}')
  context.extend(properties)
  
  
  # print
  jsonString = '{ "@context": {' + ','.join(context) + ' } }' # end context and file
  print(json.dumps(json.loads(jsonString), indent=2))

  filename = prefix + ".json"
  f = open(filename, "w")
  f.write(json.dumps(json.loads(jsonString), indent=2))
  f.close()
None

Author: Martin G. Skjæveland

Created: 2023-08-17 to. 21:38

Validate