forked from cmo/triple-tools
49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
import argparse
|
|
import io
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from dump_things_service.converter import Format, FormatConverter
|
|
from rdflib import Graph
|
|
|
|
|
|
argument_parser = argparse.ArgumentParser()
|
|
argument_parser.add_argument('--schema', '-s', required=True,)
|
|
argument_parser.add_argument('--class', '-c', dest='class_name', default=None)
|
|
argument_parser.add_argument('input_file', nargs='?', default='')
|
|
|
|
|
|
arguments = argument_parser.parse_args()
|
|
|
|
if arguments.input_file == '':
|
|
input_ = sys.stdin
|
|
else:
|
|
input_ = Path(arguments.input_file).open('rt')
|
|
|
|
converter = FormatConverter(arguments.schema, input_format=Format.json, output_format=Format.ttl)
|
|
|
|
g = Graph()
|
|
|
|
json_objects = json.load(input_)
|
|
for json_object in json_objects:
|
|
object_class = json_object.get('schema_type')
|
|
if object_class is None:
|
|
class_name = arguments.class_name
|
|
if class_name is None:
|
|
raise ValueError(f'No schema_type in {json_object}, use --class/-c to specify the class for all objects')
|
|
else:
|
|
class_name = re.search('([_A-Za-z0-9]*$)', object_class).group(0)
|
|
if arguments.class_name:
|
|
if class_name != arguments.classs_name:
|
|
raise ValueError(f'schema_type ({class_name}) does not match provided class name ({arguments.class_name})')
|
|
|
|
ttl = converter.convert(json_object, class_name)
|
|
print('----------------------', file=sys.stderr)
|
|
print(json.dumps(json_object, indent=2), file=sys.stderr)
|
|
print(ttl, file=sys.stderr)
|
|
g.parse(io.StringIO(ttl), format='n3')
|
|
|
|
|
|
print(g.serialize(format='nt'))
|