convert method

  1. @override
String convert(
  1. RdfGraph graph, {
  2. String? baseUri,
})
override

Converts an RDF graph to a JSON-LD string representation.

This method analyzes the graph structure and automatically determines the most appropriate JSON-LD representation:

  • For empty graphs, it returns an empty JSON object {}
  • For graphs with a single subject, it creates a single JSON-LD object with all properties of that subject
  • For graphs with multiple subjects, it creates a JSON-LD document with a top-level @graph array containing all subject nodes

The method also:

  • Generates consistent labels for blank nodes
  • Creates a @context object with meaningful prefixes based on the graph content
  • Groups triples by subject for better structure
  • Handles typed literals appropriately

graph The RDF graph to convert to JSON-LD. baseUri Optional base URI for relative IRIs (not currently used).

Returns a formatted JSON-LD string with 2-space indentation.

Implementation

@override
String convert(RdfGraph graph, {String? baseUri}) {
  _log.info('Serializing graph to JSON-LD');

  // Return empty JSON object for empty graph
  if (graph.isEmpty) {
    return '{}';
  }

  // Map for tracking BlankNodeTerm to label assignments
  final Map<BlankNodeTerm, String> blankNodeLabels = {};
  _generateBlankNodeLabels(graph, blankNodeLabels);

  // Create context with prefixes
  final context = _createContext(graph, _options.customPrefixes);

  // Group triples by subject
  final subjectGroups = _groupTriplesBySubject(graph.triples);

  // Check if we have only one subject group or multiple
  // For a single subject we create a JSON object, for multiple we use a JSON array
  if (subjectGroups.length == 1) {
    final Map<String, dynamic> result = {'@context': context};

    // Add the single subject node
    final entry = subjectGroups.entries.first;
    final subjectNode = _createNodeObject(
      entry.key,
      entry.value,
      context,
      blankNodeLabels,
    );
    result.addAll(subjectNode);

    return JsonEncoder.withIndent('  ').convert(result);
  } else {
    // Create a @graph structure for multiple subjects
    final Map<String, dynamic> result = {
      '@context': context,
      '@graph':
          subjectGroups.entries.map((entry) {
            return _createNodeObject(
              entry.key,
              entry.value,
              context,
              blankNodeLabels,
            );
          }).toList(),
    };

    return JsonEncoder.withIndent('  ').convert(result);
  }
}