Class: JSON::LD::Writer

Inherits:
RDF::Writer show all
Includes:
StreamingWriter, Utils, RDF::Util::Logger
Defined in:
vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb

Overview

A JSON-LD parser in Ruby.

Note that the natural interface is to write a whole graph at a time. Writing statements or Triples will create a graph to add them to and then serialize the graph.

The writer will add prefix definitions, and use them for creating @context definitions, and minting CURIEs

Select the :expand option to output JSON-LD in expanded form

Examples:

Obtaining a JSON-LD writer class

RDF::Writer.for(:jsonld)         #=> JSON::LD::Writer
RDF::Writer.for("etc/test.json")
RDF::Writer.for(:file_name      => "etc/test.json")
RDF::Writer.for(file_extension: "json")
RDF::Writer.for(:content_type   => "application/turtle")

Serializing RDF graph into an JSON-LD file

JSON::LD::Writer.open("etc/test.json") do |writer|
  writer << graph
end

Serializing RDF statements into an JSON-LD file

JSON::LD::Writer.open("etc/test.json") do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Serializing RDF statements into an JSON-LD string

JSON::LD::Writer.buffer do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Creating @@context prefix definitions in output

JSON::LD::Writer.buffer(
  prefixes: {
    nil => "http://example.com/ns#",
    foaf: "http://xmlns.com/foaf/0.1/"}
) do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

See Also:

Author:

Instance Attribute Summary collapse

Attributes inherited from RDF::Writer

#options

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RDF::Util::Logger

#log_debug, #log_depth, #log_error, #log_fatal, #log_info, #log_recover, #log_recovering?, #log_statistics, #log_warn, #logger

Methods included from Utils

#add_value, #as_resource, #blank_node?, #compare_values, #graph?, #has_property, #has_value, #index?, #list?, #node?, #node_or_ref?, #node_reference?, #simple_graph?, #value?

Methods included from StreamingWriter

#stream_epilogue, #stream_prologue, #stream_statement

Methods inherited from RDF::Writer

#base_uri, buffer, #canonicalize?, dump, each, #encoding, #escaped, #flush, for, format, #format_list, #format_literal, #format_node, #format_term, #format_uri, #node_id, open, #prefix, #prefixes, #prefixes=, #puts, #quoted, #to_sym, to_sym, #uri_for, #validate?, #write_comment, #write_statement, #write_triples

Methods included from RDF::Util::Aliasing::LateBound

#alias_method

Methods included from RDF::Writable

#<<, #insert, #insert_graph, #insert_reader, #insert_statement, #insert_statements, #writable?

Constructor Details

#initialize(output = $stdout, options = {}) {|writer| ... } ⇒ Writer

Initializes the RDF-LD writer instance.

Parameters:

  • output (IO, File) (defaults to: $stdout)

    the output stream

  • options (Hash{Symbol => Object}) (defaults to: {})

    any additional options

Options Hash (options):

  • :encoding (Encoding) — default: Encoding::UTF_8

    the encoding to use on the output stream (Ruby 1.9+)

  • :canonicalize (Boolean) — default: false

    whether to canonicalize literals when serializing

  • :prefixes (Hash) — default: {}

    the prefix mappings to use (not supported by all writers)

  • :standard_prefixes (Boolean) — default: false

    Add standard prefixes to @prefixes, if necessary.

  • :context (IO, Array, Hash, String, Context) — default: {}

    context to use when serializing. Constructed context for native serialization.

  • :frame (IO, Array, Hash, String, Context) — default: {}

    frame to use when serializing.

  • :unique_bnodes (Boolean) — default: false

    Use unique bnode identifiers, defaults to using the identifier which the node was originall initialized with (if any).

  • :stream (Boolean) — default: false

    Do not attempt to optimize graph presentation, suitable for streaming large graphs.

Yields:

  • (writer)

    self

  • (writer)

Yield Parameters:

Yield Returns:

  • (void)


142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 142

def initialize(output = $stdout, options = {}, &block)
  options[:base_uri] ||= options[:base] if options.has_key?(:base)
  options[:base] ||= options[:base_uri] if options.has_key?(:base_uri)
  super do
    @repo = RDF::Repository.new

    if block_given?
      case block.arity
        when 0 then instance_eval(&block)
        else block.call(self)
      end
    end
  end
end

Instance Attribute Details

#contextContext (readonly)

Returns context used to load and administer contexts

Returns:

  • (Context)

    context used to load and administer contexts



68
69
70
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 68

def context
  @context
end

#graphRDF::Graph (readonly)

Returns Graph of statements serialized

Returns:



64
65
66
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 64

def graph
  @graph
end

Class Method Details

.optionsObject

JSON-LD Writer options



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 73

def self.options
  super + [
    RDF::CLI::Option.new(
      symbol: :compactArrays,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--compact-arrays"],
      description: "Replaces arrays with just one element with that element during compaction.") {true},
    RDF::CLI::Option.new(
      symbol: :compactToRelative,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--compact-to-relative"],
      description: "Creates document relative IRIs when compacting, if `true`, otherwise leaves expanded. Default is `true` use --no-compact-to-relative to disable.") {true},
    RDF::CLI::Option.new(
      symbol: :context,
      datatype: RDF::URI,
      control: :url2,
      on: ["--context CONTEXT"],
      description: "Context to use when compacting.") {|arg| RDF::URI(arg)},
    RDF::CLI::Option.new(
      symbol: :processing_mode,
      datatype: %w(json-ld-1.0 json-ld-1.1),
      control: :radio,
      on: ["--processingMode MODE", %w(json-ld-1.0 json-ld-1.1)],
      description: "Set Processing Mode (json-ld-1.0 or json-ld-1.1)"),
    RDF::CLI::Option.new(
      symbol: :stream,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--stream"],
      description: "Do not attempt to optimize graph presentation, suitable for streaming large graphs.") {true},
    RDF::CLI::Option.new(
      symbol: :useRdfType,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--use-rdf-type"],
      description: "Treat `rdf:type` like a normal property instead of using `@type`.") {true},
  ]
end

Instance Method Details

#write_epilogue

This method returns an undefined value.

Outputs the Serialized JSON-LD representation of all stored statements.

If provided a context or prefixes, we'll create a context and use it to compact the output. Otherwise, we return un-compacted JSON-LD

See Also:



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 200

def write_epilogue
  if @options[:stream]
    stream_epilogue
  else

    log_debug("writer") { "serialize #{@repo.count} statements, #{@options.inspect}"}
    result = API.fromRdf(@repo, @options)

    # If we were provided a context, or prefixes, use them to compact the output
    context = RDF::Util::File.open_file(@options[:context]) if @options[:context].is_a?(String)
    context ||= @options[:context]
    context ||= if @options[:prefixes] || @options[:language] || @options[:standard_prefixes]
      ctx = Context.new(@options)
      ctx.language = @options[:language] if @options[:language]
      @options[:prefixes].each do |prefix, iri|
        ctx.set_mapping(prefix, iri) if prefix && iri
      end if @options[:prefixes]
      ctx
    end

    # Rename BNodes to uniquify them, if necessary
    if options[:unique_bnodes]
      result = API.flatten(result, context, @options)
    end

    frame = RDF::Util::File.open_file(@options[:frame]) if @options[:frame].is_a?(String)
    if frame ||= @options[:frame]
      # Perform framing, if given a frame
      log_debug("writer") { "frame result"}
      result = API.frame(result, frame, @options)
    elsif context
      # Perform compaction, if we have a context
      log_debug("writer") { "compact result"}
      result = API.compact(result, context,  @options)
    end

    @output.write(result.to_json(JSON_STATE))
  end

  super
end

#write_prologue

This method returns an undefined value.

Necessary for streaming



187
188
189
190
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 187

def write_prologue
  stream_prologue if @options[:stream]
  super
end

#write_quad(subject, predicate, object, graph_name)

This method returns an undefined value.

Outputs the N-Quads representation of a statement.

Parameters:



175
176
177
178
179
180
181
182
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 175

def write_quad(subject, predicate, object, graph_name)
  statement = RDF::Statement.new(subject, predicate, object, graph_name: graph_name)
  if @options[:stream]
    stream_statement(statement)
  else
    @repo.insert(statement)
  end
end

#write_triple(subject, predicate, object)

This method is abstract.

This method returns an undefined value.

Addes a triple to be serialized

Parameters:



164
165
166
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/json-ld-10f0d539c024/lib/json/ld/writer.rb', line 164

def write_triple(subject, predicate, object)
  write_quad(subject, predicate, object, nil)
end