ld

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 9, 2020 License: Apache-2.0 Imports: 19 Imported by: 274

Documentation

Index

Examples

Constants

View Source
const (
	JsonLd_1_0       = "json-ld-1.0"
	JsonLd_1_1       = "json-ld-1.1"
	JsonLd_1_1_Frame = "json-ld-1.1-expand-frame"

	EmbedLast   = "@last"
	EmbedAlways = "@always"
	EmbedNever  = "@never"
)
View Source
const (
	RDFSyntaxNS string = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
	RDFSchemaNS string = "http://www.w3.org/2000/01/rdf-schema#"
	XSDNS       string = "http://www.w3.org/2001/XMLSchema#"

	XSDAnyType string = XSDNS + "anyType"
	XSDBoolean string = XSDNS + "boolean"
	XSDDouble  string = XSDNS + "double"
	XSDInteger string = XSDNS + "integer"
	XSDFloat   string = XSDNS + "float"
	XSDDecimal string = XSDNS + "decimal"
	XSDAnyURI  string = XSDNS + "anyURI"
	XSDString  string = XSDNS + "string"

	RDFType         string = RDFSyntaxNS + "type"
	RDFFirst        string = RDFSyntaxNS + "first"
	RDFRest         string = RDFSyntaxNS + "rest"
	RDFNil          string = RDFSyntaxNS + "nil"
	RDFPlainLiteral string = RDFSyntaxNS + "PlainLiteral"
	RDFXMLLiteral   string = RDFSyntaxNS + "XMLLiteral"
	RDFJSONLiteral  string = RDFSyntaxNS + "JSON"
	RDFObject       string = RDFSyntaxNS + "object"
	RDFLangString   string = RDFSyntaxNS + "langString"
	RDFList         string = RDFSyntaxNS + "List"
)

Variables

View Source
var (
	IP           = `` /* 659-byte string literal not displayed */
	URLSchema    = `((ftp|tcp|udp|wss?|https?):\/\/)`
	URLUsername  = `(\S+(:\S*)?@)`
	URLPath      = `((\/|\?|#)[^\s]*)`
	URLPort      = `(:(\d{1,5}))`
	URLIP        = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
	URLSubdomain = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
	URL          = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$`
)

=========== The URL validation logic below was borrowed from github.com/asaskevich/govalidator package. The original code is distributed under MIT license. Copyright (c) 2014 Alex Saskevich ===========

View Source
var (
	Positions = []string{"s", "o", "g"}
)

Functions

func AddValue added in v0.2.0

func AddValue(subject interface{}, property string, value interface{}, propertyIsArray, valueAsArray, allowDuplicate,
	prependValue bool)

AddValue adds a value to a subject. If the value is an array, all values in the array will be added.

Options:

[propertyIsArray] True if the property is always an array, False if not (default: False).
[allowDuplicate] True to allow duplicates, False not to (uses a simple shallow comparison
		of subject ID or value) (default: True).

func Arrayify added in v0.2.0

func Arrayify(v interface{}) []interface{}

Arrayify returns v, if v is an array, otherwise returns an array containing v as the only element.

func CloneDocument

func CloneDocument(value interface{}) interface{}

CloneDocument returns a cloned instance of the given document

func CompareShortestLeast

func CompareShortestLeast(a string, b string) bool

CompareShortestLeast compares two strings first based on length and then lexicographically.

func CompareValues

func CompareValues(v1 interface{}, v2 interface{}) bool

CompareValues compares two JSON-LD values for equality. Two JSON-LD values will be considered equal if:

1. They are both primitives of the same type and value. 2. They are both @values with the same @value, @type, and @language, OR 3. They both have @ids they are the same.

func DeepCompare

func DeepCompare(v1 interface{}, v2 interface{}, listOrderMatters bool) bool

DeepCompare returns true if v1 equals v2.

func DocumentFromReader

func DocumentFromReader(r io.Reader) (interface{}, error)

DocumentFromReader returns a document containing the contents of the JSON resource, streamed from the given Reader.

func FilterSubject added in v0.2.0

func FilterSubject(state *FramingContext, subject map[string]interface{}, frame map[string]interface{}, requireAll bool) (bool, error)

FilterSubject returns true if the given node matches the given frame.

Matches either based on explicit type inclusion where the node has any type listed in the frame. If the frame has empty types defined matches nodes not having a @type. If the frame has a type of {} defined matches nodes having any type defined.

Otherwise, does duck typing, where the node must have all of the properties defined in the frame.

func FilterSubjects added in v0.2.0

func FilterSubjects(state *FramingContext, subjects []string, frame map[string]interface{}, requireAll bool) (map[string]interface{}, error)

FilterSubjects returns a map of all of the nodes that match a parsed frame.

func GetCanonicalDouble

func GetCanonicalDouble(v float64) string

GetCanonicalDouble returns a canonical string representation of a float64 number.

func GetFrameFlag

func GetFrameFlag(frame map[string]interface{}, name string, theDefault bool) bool

GetFrameFlag gets the frame flag value for the given flag name. If boolean value is not found, returns theDefault

func GetKeys

func GetKeys(m map[string]interface{}) []string

GetKeys returns all keys in the given object

func GetKeysString

func GetKeysString(m map[string]string) []string

GetKeysString returns all keys in the given map[string]string

func GetOrderedKeys

func GetOrderedKeys(m map[string]interface{}) []string

GetOrderedKeys returns all keys in the given object as a sorted list

func HasValue added in v0.2.0

func HasValue(subject interface{}, property string, value interface{}) bool

HasValue determines if the given value is a property of the given subject

func InvalidNode added in v0.3.0

func InvalidNode(node Node) bool

func IsAbsoluteIri

func IsAbsoluteIri(value string) bool

IsAbsoluteIri returns true if the given value is an absolute IRI, false if not.

func IsBlankNode

func IsBlankNode(node Node) bool

IsBlankNode returns true if the given node is a blank node

func IsBlankNodeValue

func IsBlankNodeValue(v interface{}) bool

IsBlankNode returns true if the given value is a blank node.

func IsGraph added in v0.2.0

func IsGraph(v interface{}) bool

IsGraph returns true if the given value is a graph.

Note: A value is a graph if all of these hold true: 1. It is an object. 2. It has an `@graph` key. 3. It may have '@id' or '@index'

func IsIRI

func IsIRI(node Node) bool

IsIRI returns true if the given node is an IRI node

func IsKeyword

func IsKeyword(key interface{}) bool

IsKeyword returns whether or not the given value is a keyword.

func IsList added in v0.2.0

func IsList(v interface{}) bool

IsList returns true if the given value is a @list.

func IsLiteral

func IsLiteral(node Node) bool

IsLiteral returns true if the given node is a literal node

func IsReferencedOnce

func IsReferencedOnce(node *NodeMapNode, referencedOnce map[string]*UsagesNode) bool

IsReferencedOnce helps to solve https://github.com/json-ld/json-ld.org/issues/357 by identifying nodes with just one reference.

func IsRelativeIri

func IsRelativeIri(value string) bool

IsRelativeIri returns true if the given value is a relative IRI, false if not.

func IsSimpleGraph added in v0.2.0

func IsSimpleGraph(v interface{}) bool

IsSimpleGraph returns true if the given value is a simple @graph

func IsSubject added in v0.2.0

func IsSubject(v interface{}) bool

IsSubject returns true if the given value is a subject with properties.

Note: A value is a subject if all of these hold true: 1. It is an Object. 2. It is not a @value, @set, or @list. 3. It has more than 1 key OR any existing key is not @id.

func IsSubjectReference added in v0.2.0

func IsSubjectReference(v interface{}) bool

IsSubjectReference returns true if the given value is a subject reference.

Note: A value is a subject reference if all of these hold True: 1. It is an Object. 2. It has a single key: @id.

func IsURL added in v0.3.0

func IsURL(str string) bool

IsURL check if the string is an URL.

func IsValue

func IsValue(v interface{}) bool

IsValue returns true if the given value is a JSON-LD value

func MergeValue

func MergeValue(obj map[string]interface{}, key string, value interface{})

MergeValue adds a value to a subject. If the value is an array, all values in the array will be added.

func ParseLinkHeader

func ParseLinkHeader(header string) map[string][]map[string]string

ParseLinkHeader parses a link header. The results will be keyed by the value of "rel".

Link: <http://json-ld.org/contexts/person.jsonld>; \
  rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json"
Parses as: {
  'http://www.w3.org/ns/json-ld#context': {
    target: http://json-ld.org/contexts/person.jsonld,
    rel:    http://www.w3.org/ns/json-ld#context
  }
}

If there is more than one "rel" with the same IRI, then entries in the resulting map for that "rel" will be lists.

func PrintDocument

func PrintDocument(msg string, doc interface{})

PrintDocument prints a JSON-LD document. This is useful for debugging.

func RemoveBase

func RemoveBase(baseobj interface{}, iri string) string

RemoveBase removes base URL from the given IRI.

func RemovePreserve

func RemovePreserve(ctx *Context, input interface{}, bnodesToClear []string, compactArrays bool) (interface{}, error)

RemovePreserve removes the @preserve keywords as the last step of the framing algorithm.

ctx: the active context used to compact the input input: the framed, compacted output bnodesToClear: list of bnodes to be pruned compactArrays: compactArrays flag

Returns the resulting output.

func RemoveValue added in v0.2.0

func RemoveValue(subject interface{}, property string, value interface{}, propertyIsArray bool)

RemoveValue removes a value from a subject.

func Resolve

func Resolve(baseURI string, pathToResolve string) string

Resolve the given path against the given base URI. Returns a full URI.

Types

type BlankNode

type BlankNode struct {
	Attribute string
}

BlankNode represents a blank node value.

func NewBlankNode

func NewBlankNode(attribute string) *BlankNode

NewBlankNode creates a new instance of BlankNode.

func (BlankNode) Equal

func (bn BlankNode) Equal(n Node) bool

Equal returns true id this node is equal to the given node.

func (BlankNode) GetValue

func (bn BlankNode) GetValue() string

GetValue returns the node's value.

type CachingDocumentLoader

type CachingDocumentLoader struct {
	// contains filtered or unexported fields
}

CachingDocumentLoader is an overlay on top of DocumentLoader instance which allows caching documents as soon as they get retrieved from the underlying loader. You may also preload it with documents - this is useful for testing.

func NewCachingDocumentLoader

func NewCachingDocumentLoader(nextLoader DocumentLoader) *CachingDocumentLoader

NewCachingDocumentLoader creates a new instance of CachingDocumentLoader.

func (*CachingDocumentLoader) AddDocument

func (cdl *CachingDocumentLoader) AddDocument(u string, doc interface{})

AddDocument populates the cache with the given document (doc) for the provided URL (u).

func (*CachingDocumentLoader) LoadDocument

func (cdl *CachingDocumentLoader) LoadDocument(u string) (*RemoteDocument, error)

LoadDocument returns a RemoteDocument containing the contents of the JSON resource from the given URL.

func (*CachingDocumentLoader) PreloadWithMapping

func (cdl *CachingDocumentLoader) PreloadWithMapping(urlMap map[string]string) error

PreloadWithMapping populates the cache with a number of documents which may be loaded from location different from the original URL (most importantly, from local files).

Example:

l.PreloadWithMapping(map[string]string{
    "http://www.example.com/context.json": "/home/me/cache/example_com_context.json",
})

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context represents a JSON-LD context and provides easy access to specific keys and operations.

func CopyContext

func CopyContext(ctx *Context) *Context

CopyContext creates a full copy of the given context.

func NewContext

func NewContext(values map[string]interface{}, options *JsonLdOptions) *Context

NewContext creates and returns a new Context object.

func (*Context) AsMap added in v0.3.0

func (c *Context) AsMap() map[string]interface{}

func (*Context) CompactIri

func (c *Context) CompactIri(iri string, value interface{}, relativeToVocab bool, reverse bool) (string, error)

CompactIri compacts an IRI or keyword into a term or CURIE if it can be. If the IRI has an associated value it may be passed.

iri: the IRI to compact. value: the value to check or None. relativeToVocab: true to compact using @vocab if available, false not to. reverse: true if a reverse property is being compacted, false if not.

Returns the compacted term, prefix, keyword alias, or original IRI.

func (*Context) CompactValue

func (c *Context) CompactValue(activeProperty string, value map[string]interface{}) (interface{}, error)

CompactValue performs value compaction on an object with @value or @id as the only property. See https://www.w3.org/TR/2019/CR-json-ld11-api-20191212/#value-compaction

func (*Context) ExpandIri

func (c *Context) ExpandIri(value string, relative bool, vocab bool, context map[string]interface{},
	defined map[string]bool) (string, error)

ExpandIri expands a string value to a full IRI.

The string may be a term, a prefix, a relative IRI, or an absolute IRI. The associated absolute IRI will be returned.

value: the string value to expand. relative: true to resolve IRIs against the base IRI, false not to. vocab: true to concatenate after @vocab, false not to. context: the local context being processed (only given if called during context processing). defined: a map for tracking cycles in context definitions (only given if called during context processing).

func (*Context) ExpandValue

func (c *Context) ExpandValue(activeProperty string, value interface{}) (interface{}, error)

ExpandValue expands the given value by using the coercion and keyword rules in the context.

func (*Context) GetContainer

func (c *Context) GetContainer(property string) []interface{}

GetContainer retrieves container mapping for the given property.

func (*Context) GetDirectionMapping added in v0.3.0

func (c *Context) GetDirectionMapping(property string) interface{}

GetDirectionMapping returns direction mapping for the given property

func (*Context) GetInverse

func (c *Context) GetInverse() map[string]interface{}

GetInverse generates an inverse context for use in the compaction algorithm, if not already generated for the given active context. See http://www.w3.org/TR/json-ld-api/#inverse-context-creation for further details.

func (*Context) GetLanguageMapping

func (c *Context) GetLanguageMapping(property string) interface{}

GetLanguageMapping returns language mapping for the given property

func (*Context) GetPrefixes

func (c *Context) GetPrefixes(onlyCommonPrefixes bool) map[string]string

GetPrefixes returns a map of potential RDF prefixes based on the JSON-LD Term Definitions in this context. No guarantees of the prefixes are given, beyond that it will not contain ":".

onlyCommonPrefixes: If true, the result will not include "not so useful" prefixes, such as "term1": "http://example.com/term1", e.g. all IRIs will end with "/" or "#". If false, all potential prefixes are returned.

Returns a map from prefix string to IRI string

func (*Context) GetTermDefinition

func (c *Context) GetTermDefinition(key string) map[string]interface{}

GetTermDefinition returns a term definition for the given key

func (*Context) GetTypeMapping

func (c *Context) GetTypeMapping(property string) string

GetTypeMapping returns type mapping for the given property

func (*Context) HasContainerMapping added in v0.2.0

func (c *Context) HasContainerMapping(property string, val string) bool

GetContainer retrieves container mapping for the given property.

func (*Context) IsReverseProperty

func (c *Context) IsReverseProperty(property string) bool

IsReverseProperty returns true if the given property is a reverse property

func (*Context) Parse

func (c *Context) Parse(localContext interface{}) (*Context, error)

Parse processes a local context, retrieving any URLs as necessary, and returns a new active context. Refer to http://www.w3.org/TR/json-ld-api/#context-processing-algorithms for details TODO pyLD is doing a fair bit more in process_context(self, active_ctx, local_ctx, options) than just parsing the context. In particular, we need to check if additional logic is required to load remote scoped contexts.

func (*Context) RevertToPreviousContext added in v0.3.0

func (c *Context) RevertToPreviousContext() *Context

RevertToPreviousContext reverts any type-scoped context in this active context to the previous context.

func (*Context) SelectTerm

func (c *Context) SelectTerm(iri string, containers []string, typeLanguage string, preferredValues []string) string

SelectTerm picks the preferred compaction term from the inverse context entry. See http://www.w3.org/TR/json-ld-api/#term-selection

This algorithm, invoked via the IRI Compaction algorithm, makes use of an active context's inverse context to find the term that is best used to compact an IRI. Other information about a value associated with the IRI is given, including which container mappings and which type mapping or language mapping would be best used to express the value.

func (*Context) Serialize

func (c *Context) Serialize() (map[string]interface{}, error)

Serialize transforms the context back into JSON form.

type DefaultDocumentLoader

type DefaultDocumentLoader struct {
	// contains filtered or unexported fields
}

DefaultDocumentLoader is a standard implementation of DocumentLoader which can retrieve documents via HTTP.

func NewDefaultDocumentLoader

func NewDefaultDocumentLoader(httpClient *http.Client) *DefaultDocumentLoader

NewDefaultDocumentLoader creates a new instance of DefaultDocumentLoader

func (*DefaultDocumentLoader) LoadDocument

func (dl *DefaultDocumentLoader) LoadDocument(u string) (*RemoteDocument, error)

LoadDocument returns a RemoteDocument containing the contents of the JSON resource from the given URL.

type DocumentLoader

type DocumentLoader interface {
	LoadDocument(u string) (*RemoteDocument, error)
}

DocumentLoader knows how to load remote documents.

type Embed

type Embed string

type EmbedNode

type EmbedNode struct {
	// contains filtered or unexported fields
}

EmbedNode represents embed meta info

type ErrorCode

type ErrorCode string

ErrorCode is a JSON-LD error code as per spec.

const (
	LoadingDocumentFailed       ErrorCode = "loading document failed"
	InvalidIndexValue           ErrorCode = "invalid @index value"
	ConflictingIndexes          ErrorCode = "conflicting indexes"
	InvalidIDValue              ErrorCode = "invalid @id value"
	InvalidLocalContext         ErrorCode = "invalid local context"
	MultipleContextLinkHeaders  ErrorCode = "multiple context link headers"
	LoadingRemoteContextFailed  ErrorCode = "loading remote context failed"
	InvalidRemoteContext        ErrorCode = "invalid remote context"
	RecursiveContextInclusion   ErrorCode = "recursive context inclusion"
	InvalidBaseIRI              ErrorCode = "invalid base IRI"
	InvalidVocabMapping         ErrorCode = "invalid vocab mapping"
	InvalidDefaultLanguage      ErrorCode = "invalid default language"
	KeywordRedefinition         ErrorCode = "keyword redefinition"
	InvalidTermDefinition       ErrorCode = "invalid term definition"
	InvalidReverseProperty      ErrorCode = "invalid reverse property"
	InvalidIRIMapping           ErrorCode = "invalid IRI mapping"
	CyclicIRIMapping            ErrorCode = "cyclic IRI mapping"
	InvalidKeywordAlias         ErrorCode = "invalid keyword alias"
	InvalidTypeMapping          ErrorCode = "invalid type mapping"
	InvalidLanguageMapping      ErrorCode = "invalid language mapping"
	CollidingKeywords           ErrorCode = "colliding keywords"
	InvalidContainerMapping     ErrorCode = "invalid container mapping"
	InvalidTypeValue            ErrorCode = "invalid type value"
	InvalidValueObject          ErrorCode = "invalid value object"
	InvalidValueObjectValue     ErrorCode = "invalid value object value"
	InvalidLanguageTaggedString ErrorCode = "invalid language-tagged string"
	InvalidLanguageTaggedValue  ErrorCode = "invalid language-tagged value"
	InvalidTypedValue           ErrorCode = "invalid typed value"
	InvalidSetOrListObject      ErrorCode = "invalid set or list object"
	InvalidLanguageMapValue     ErrorCode = "invalid language map value"
	InvalidReversePropertyMap   ErrorCode = "invalid reverse property map"
	InvalidReverseValue         ErrorCode = "invalid @reverse value"
	InvalidReversePropertyValue ErrorCode = "invalid reverse property value"
	InvalidVersionValue         ErrorCode = "invalid @version value"
	ProcessingModeConflict      ErrorCode = "processing mode conflict"
	InvalidFrame                ErrorCode = "invalid frame"
	InvalidEmbedValue           ErrorCode = "invalid @embed value"
	InvalidPrefixValue          ErrorCode = "invalid @prefix value"
	InvalidNestValue            ErrorCode = "invalid @nest value"
	InvalidContextNullification ErrorCode = "invalid context nullification"
	ProtectedTermRedefinition   ErrorCode = "protected term redefinition"
	InvalidContextMember        ErrorCode = "invalid context member"
	InvalidPropagateValue       ErrorCode = "invalid @propagate value"
	InvalidBaseDirection        ErrorCode = "invalid base direction"
	InvalidIncludedValue        ErrorCode = "invalid @included value"
	InvalidImportValue          ErrorCode = "invalid @import value"
	IRIConfusedWithPrefix       ErrorCode = "IRI confused with prefix"

	// non spec related errors
	SyntaxError    ErrorCode = "syntax error"
	NotImplemented ErrorCode = "not implemented"
	UnknownFormat  ErrorCode = "unknown format"
	InvalidInput   ErrorCode = "invalid input"
	ParseError     ErrorCode = "parse error"
	IOError        ErrorCode = "io error"
	UnknownError   ErrorCode = "unknown error"
)

type FramingContext

type FramingContext struct {
	// contains filtered or unexported fields
}

FramingContext stores framing state

func NewFramingContext

func NewFramingContext(opts *JsonLdOptions) *FramingContext

NewFramingContext creates and returns as new framing context.

type IRI

type IRI struct {
	Value string
}

IRI represents an IRI value.

func NewIRI

func NewIRI(iri string) *IRI

NewIRI creates a new instance of IRI.

func (IRI) Equal

func (iri IRI) Equal(n Node) bool

Equal returns true id this node is equal to the given node.

func (IRI) GetValue

func (iri IRI) GetValue() string

GetValue returns the node's value.

type IdentifierIssuer

type IdentifierIssuer struct {
	// contains filtered or unexported fields
}

IdentifierIssuer issues unique identifiers, keeping track of any previously issued identifiers.

func NewIdentifierIssuer

func NewIdentifierIssuer(prefix string) *IdentifierIssuer

NewIdentifierIssuer creates and returns a new IdentifierIssuer.

func (*IdentifierIssuer) Clone

func (ii *IdentifierIssuer) Clone() *IdentifierIssuer

Clone copies this IdentifierIssuer.

func (*IdentifierIssuer) GetId

func (ii *IdentifierIssuer) GetId(oldId string) string

GetId Gets the new identifier for the given old identifier, where if no old identifier is given a new identifier will be generated.

func (*IdentifierIssuer) HasId

func (ii *IdentifierIssuer) HasId(oldId string) bool

HasId returns True if the given old identifier has already been assigned a new identifier.

type JsonLdApi

type JsonLdApi struct {
}

JsonLdApi exposes internal functions used by JsonLdProcessor. See http://www.w3.org/TR/json-ld-api/ for detailed description of underlying algorithms

Warning: using this interface directly is highly discouraged. Please use JsonLdProcessor instead.

func NewJsonLdApi

func NewJsonLdApi() *JsonLdApi

NewJsonLdApi creates a new instance of JsonLdApi.

func (*JsonLdApi) Compact

func (api *JsonLdApi) Compact(activeCtx *Context, activeProperty string, element interface{},
	compactArrays bool) (interface{}, error)

Compact operation compacts the given input using the context according to the steps in the Compaction Algorithm:

http://www.w3.org/TR/json-ld-api/#compaction-algorithm

Returns the compacted JSON-LD object. Returns an error if there was an error during compaction.

func (*JsonLdApi) Expand

func (api *JsonLdApi) Expand(activeCtx *Context, activeProperty string, element interface{}, opts *JsonLdOptions, insideIndex bool, typeScopedContext *Context) (interface{}, error)

Expand operation expands the given input according to the steps in the Expansion algorithm:

http://www.w3.org/TR/json-ld-api/#expansion-algorithm

Returns the expanded JSON-LD object. Returns an error if there was an error during expansion.

func (*JsonLdApi) Frame

func (api *JsonLdApi) Frame(input interface{}, frame []interface{}, opts *JsonLdOptions, merged bool) ([]interface{}, []string, error)

Frame performs JSON-LD framing as defined in:

http://json-ld.org/spec/latest/json-ld-framing/

Frames the given input using the frame according to the steps in the Framing Algorithm. The input is used to build the framed output and is returned if there are no errors.

Returns the framed output.

func (*JsonLdApi) FromRDF

func (api *JsonLdApi) FromRDF(dataset *RDFDataset, opts *JsonLdOptions) ([]interface{}, error)

FromRDF converts RDF statements into JSON-LD. Returns a list of JSON-LD objects found in the given dataset.

func (*JsonLdApi) GenerateNodeMap

func (api *JsonLdApi) GenerateNodeMap(element interface{}, graphMap map[string]interface{}, activeGraph string,
	issuer *IdentifierIssuer, activeSubject interface{}, activeProperty string, list map[string]interface{}) (map[string]interface{}, error)

GenerateNodeMap recursively flattens the subjects in the given JSON-LD expanded input into a node map.

func (*JsonLdApi) Normalize

func (api *JsonLdApi) Normalize(dataset *RDFDataset, opts *JsonLdOptions) (interface{}, error)

func (*JsonLdApi) ToRDF

func (api *JsonLdApi) ToRDF(input interface{}, opts *JsonLdOptions) (*RDFDataset, error)

ToRDF adds RDF triples for each graph in the current node map to an RDF dataset.

type JsonLdError

type JsonLdError struct {
	Code    ErrorCode
	Details interface{}
}

JsonLdError is a JSON-LD error as defined in the spec. See the allowed values and error messages below.

func NewJsonLdError

func NewJsonLdError(code ErrorCode, details interface{}) *JsonLdError

NewJsonLdError creates a new instance of JsonLdError.

func (JsonLdError) Error

func (e JsonLdError) Error() string

type JsonLdOptions

type JsonLdOptions struct {

	// http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-base
	Base string
	// http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-compactArrays
	CompactArrays bool
	// http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-expandContext
	ExpandContext interface{}
	// http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-processingMode
	ProcessingMode string
	// http://www.w3.org/TR/json-ld-api/#widl-JsonLdOptions-documentLoader
	DocumentLoader DocumentLoader

	Embed        Embed
	Explicit     bool
	RequireAll   bool
	FrameDefault bool
	OmitDefault  bool
	OmitGraph    bool

	UseRdfType            bool
	UseNativeTypes        bool
	ProduceGeneralizedRdf bool

	InputFormat   string
	Format        string
	Algorithm     string
	UseNamespaces bool
	OutputForm    string
}

JsonLdOptions type as specified in the JSON-LD-API specification: http://www.w3.org/TR/json-ld-api/#the-jsonldoptions-type

func NewJsonLdOptions

func NewJsonLdOptions(base string) *JsonLdOptions

NewJsonLdOptions creates and returns new instance of JsonLdOptions with the given base.

func (*JsonLdOptions) Copy added in v0.2.0

func (opt *JsonLdOptions) Copy() *JsonLdOptions

Copy creates a deep copy of JsonLdOptions object.

type JsonLdProcessor

type JsonLdProcessor struct {
}

JsonLdProcessor implements the JsonLdProcessor interface, see http://www.w3.org/TR/json-ld-api/#the-jsonldprocessor-interface

func NewJsonLdProcessor

func NewJsonLdProcessor() *JsonLdProcessor

NewJsonLdProcessor creates an instance of JsonLdProcessor.

func (*JsonLdProcessor) Compact

func (jldp *JsonLdProcessor) Compact(input interface{}, context interface{},
	opts *JsonLdOptions) (map[string]interface{}, error)

Compact operation compacts the given input using the context according to the steps in the Compaction algorithm: http://www.w3.org/TR/json-ld-api/#compaction-algorithm

Example
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	doc := map[string]interface{}{
		"@id": "http://example.org/test#book",
		"http://example.org/vocab#contains": map[string]interface{}{
			"@id": "http://example.org/test#chapter",
		},
		"http://purl.org/dc/elements/1.1/title": "Title",
	}

	context := map[string]interface{}{
		"@context": map[string]interface{}{
			"dc": "http://purl.org/dc/elements/1.1/",
			"ex": "http://example.org/vocab#",
			"ex:contains": map[string]interface{}{
				"@type": "@id",
			},
		},
	}

	compactedDoc, err := proc.Compact(doc, context, options)
	if err != nil {
		log.Println("Error when compacting JSON-LD document:", err)
		return
	}

	ld.PrintDocument("JSON-LD compact doc", compactedDoc)

}
Output:

JSON-LD compact doc
{
  "@context": {
    "dc": "http://purl.org/dc/elements/1.1/",
    "ex": "http://example.org/vocab#",
    "ex:contains": {
      "@type": "@id"
    }
  },
  "@id": "http://example.org/test#book",
  "dc:title": "Title",
  "ex:contains": "http://example.org/test#chapter"
}

func (*JsonLdProcessor) Expand

func (jldp *JsonLdProcessor) Expand(input interface{}, opts *JsonLdOptions) ([]interface{}, error)

Expand operation expands the given input according to the steps in the Expansion algorithm: http://www.w3.org/TR/json-ld-api/#expansion-algorithm

Example (Inmemory)
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	// expanding in-memory document

	doc := map[string]interface{}{
		"@context":  "http://schema.org/",
		"@type":     "Person",
		"name":      "Jane Doe",
		"jobTitle":  "Professor",
		"telephone": "(425) 123-4567",
		"url":       "http://www.janedoe.com",
	}

	expanded, err := proc.Expand(doc, options)
	if err != nil {
		log.Println("Error when expanding JSON-LD document:", err)
		return
	}

	ld.PrintDocument("JSON-LD expansion succeeded", expanded)

}
Output:

JSON-LD expansion succeeded
[
  {
    "@type": [
      "http://schema.org/Person"
    ],
    "http://schema.org/jobTitle": [
      {
        "@value": "Professor"
      }
    ],
    "http://schema.org/name": [
      {
        "@value": "Jane Doe"
      }
    ],
    "http://schema.org/telephone": [
      {
        "@value": "(425) 123-4567"
      }
    ],
    "http://schema.org/url": [
      {
        "@id": "http://www.janedoe.com"
      }
    ]
  }
]
Example (Online)
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	// expanding remote document

	expanded, err := proc.Expand("https://w3c.github.io/json-ld-api/tests/expand/0002-in.jsonld", options)
	if err != nil {
		log.Println("Error when expanding JSON-LD document:", err)
		return
	}

	ld.PrintDocument("JSON-LD expansion succeeded", expanded)

}
Output:

JSON-LD expansion succeeded
[
  {
    "@id": "http://example.com/id1",
    "@type": [
      "http://example.com/t1"
    ],
    "http://example.com/term1": [
      {
        "@value": "v1"
      }
    ],
    "http://example.com/term2": [
      {
        "@type": "http://example.com/t2",
        "@value": "v2"
      }
    ],
    "http://example.com/term3": [
      {
        "@language": "en",
        "@value": "v3"
      }
    ],
    "http://example.com/term4": [
      {
        "@value": 4
      }
    ],
    "http://example.com/term5": [
      {
        "@value": 50
      },
      {
        "@value": 51
      }
    ]
  }
]

func (*JsonLdProcessor) Flatten

func (jldp *JsonLdProcessor) Flatten(input interface{}, context interface{}, opts *JsonLdOptions) (interface{}, error)

Flatten operation flattens the given input and compacts it using the passed context according to the steps in the Flattening algorithm: http://www.w3.org/TR/json-ld-api/#flattening-algorithm

Example
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	doc := map[string]interface{}{
		"@context": []interface{}{
			map[string]interface{}{
				"name": "http://xmlns.com/foaf/0.1/name",
				"homepage": map[string]interface{}{
					"@id":   "http://xmlns.com/foaf/0.1/homepage",
					"@type": "@id",
				},
			},
			map[string]interface{}{
				"ical": "http://www.w3.org/2002/12/cal/ical#",
			},
		},
		"@id":           "http://example.com/speakers#Alice",
		"name":          "Alice",
		"homepage":      "http://xkcd.com/177/",
		"ical:summary":  "Alice Talk",
		"ical:location": "Lyon Convention Centre, Lyon, France",
	}

	flattenedDoc, err := proc.Flatten(doc, nil, options)
	if err != nil {
		log.Println("Error when flattening JSON-LD document:", err)
		return
	}

	ld.PrintDocument("JSON-LD flattened doc", flattenedDoc)

}
Output:

JSON-LD flattened doc
[
  {
    "@id": "http://example.com/speakers#Alice",
    "http://www.w3.org/2002/12/cal/ical#location": [
      {
        "@value": "Lyon Convention Centre, Lyon, France"
      }
    ],
    "http://www.w3.org/2002/12/cal/ical#summary": [
      {
        "@value": "Alice Talk"
      }
    ],
    "http://xmlns.com/foaf/0.1/homepage": [
      {
        "@id": "http://xkcd.com/177/"
      }
    ],
    "http://xmlns.com/foaf/0.1/name": [
      {
        "@value": "Alice"
      }
    ]
  }
]

func (*JsonLdProcessor) Frame

func (jldp *JsonLdProcessor) Frame(input interface{}, frame interface{}, opts *JsonLdOptions) (map[string]interface{}, error)

Frame operation frames the given input using the frame according to the steps in the Framing Algorithm: http://json-ld.org/spec/latest/json-ld-framing/#framing-algorithm

input: The input JSON-LD object frame: The frame to use when re-arranging the data of input; either in the form of an JSON object or as IRI.

Returns the framed JSON-LD document.

Example
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	doc := map[string]interface{}{
		"@context": map[string]interface{}{
			"dc":          "http://purl.org/dc/elements/1.1/",
			"ex":          "http://example.org/vocab#",
			"ex:contains": map[string]interface{}{"@type": "@id"},
		},
		"@graph": []interface{}{
			map[string]interface{}{
				"@id":         "http://example.org/test/#library",
				"@type":       "ex:Library",
				"ex:contains": "http://example.org/test#book",
			},
			map[string]interface{}{
				"@id":            "http://example.org/test#book",
				"@type":          "ex:Book",
				"dc:contributor": "Writer",
				"dc:title":       "My Book",
				"ex:contains":    "http://example.org/test#chapter",
			},
			map[string]interface{}{
				"@id":            "http://example.org/test#chapter",
				"@type":          "ex:Chapter",
				"dc:description": "Fun",
				"dc:title":       "Chapter One",
			},
		},
	}

	frame := map[string]interface{}{
		"@context": map[string]interface{}{
			"dc": "http://purl.org/dc/elements/1.1/",
			"ex": "http://example.org/vocab#",
		},
		"@type": "ex:Library",
		"ex:contains": map[string]interface{}{
			"@type": "ex:Book",
			"ex:contains": map[string]interface{}{
				"@type": "ex:Chapter",
			},
		},
	}

	framedDoc, err := proc.Frame(doc, frame, options)
	if err != nil {
		log.Println("Error when framing JSON-LD document:", err)
		return
	}

	ld.PrintDocument("JSON-LD framed doc", framedDoc)

}
Output:

JSON-LD framed doc
{
  "@context": {
    "dc": "http://purl.org/dc/elements/1.1/",
    "ex": "http://example.org/vocab#"
  },
  "@graph": [
    {
      "@id": "http://example.org/test/#library",
      "@type": "ex:Library",
      "ex:contains": {
        "@id": "http://example.org/test#book",
        "@type": "ex:Book",
        "dc:contributor": "Writer",
        "dc:title": "My Book",
        "ex:contains": {
          "@id": "http://example.org/test#chapter",
          "@type": "ex:Chapter",
          "dc:description": "Fun",
          "dc:title": "Chapter One"
        }
      }
    }
  ]
}

func (*JsonLdProcessor) FromRDF

func (jldp *JsonLdProcessor) FromRDF(dataset interface{}, opts *JsonLdOptions) (interface{}, error)

FromRDF converts an RDF dataset to JSON-LD.

dataset: a serialized string of RDF in a format specified by the format option or an RDF dataset to convert. opts: the options to use:

[format] the format if input is not an array: 'application/n-quads' for N-Quads (default).
[useRdfType] true to use rdf:type, false to use @type (default: false).
[useNativeTypes] true to convert XSD types into native types (boolean, integer, double),
false not to (default: true).
Example
package main

import (
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")

	triples := `
	<http://example.com/Subj1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.com/Type> .
	<http://example.com/Subj1> <http://example.com/prop1> <http://example.com/Obj1> .
	<http://example.com/Subj1> <http://example.com/prop2> "Plain" .
	<http://example.com/Subj1> <http://example.com/prop2> "2012-05-12"^^<http://www.w3.org/2001/XMLSchema#date> .
	<http://example.com/Subj1> <http://example.com/prop2> "English"@en .
`

	doc, err := proc.FromRDF(triples, options)
	if err != nil {
		log.Println("Error running FromRDF:", err)
		return
	}

	ld.PrintDocument("JSON-LD doc from RDF", doc)

}
Output:

JSON-LD doc from RDF
[
  {
    "@id": "http://example.com/Subj1",
    "@type": [
      "http://example.com/Type"
    ],
    "http://example.com/prop1": [
      {
        "@id": "http://example.com/Obj1"
      }
    ],
    "http://example.com/prop2": [
      {
        "@value": "Plain"
      },
      {
        "@type": "http://www.w3.org/2001/XMLSchema#date",
        "@value": "2012-05-12"
      },
      {
        "@language": "en",
        "@value": "English"
      }
    ]
  }
]

func (*JsonLdProcessor) Normalize

func (jldp *JsonLdProcessor) Normalize(input interface{}, opts *JsonLdOptions) (interface{}, error)

Normalize RDF dataset normalization on the given input. The input is JSON-LD unless the 'inputFormat' option is used. The output is an RDF dataset unless the 'format' option is used.

Example
package main

import (
	"fmt"
	"log"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")
	options.Format = "application/n-quads"
	options.Algorithm = "URDNA2015"

	doc := map[string]interface{}{
		"@context": map[string]interface{}{
			"ex": "http://example.org/vocab#",
		},
		"@id":   "http://example.org/test#example",
		"@type": "ex:Foo",
		"ex:embed": map[string]interface{}{
			"@type": "ex:Bar",
		},
	}

	normalizedTriples, err := proc.Normalize(doc, options)
	if err != nil {
		log.Println("Error running Normalize:", err)
		return
	}

	fmt.Printf("%s\n", normalizedTriples)

}
Output:

<http://example.org/test#example> <http://example.org/vocab#embed> _:c14n0 .
<http://example.org/test#example> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/vocab#Foo> .
_:c14n0 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://example.org/vocab#Bar> .

func (*JsonLdProcessor) ToRDF

func (jldp *JsonLdProcessor) ToRDF(input interface{}, opts *JsonLdOptions) (interface{}, error)

ToRDF outputs the RDF dataset found in the given JSON-LD object.

input: the JSON-LD input. opts: the options to use:

[base] the base IRI to use.
[format] the format to use to output a string: 'application/n-quads' for N-Quads (default).
Example
package main

import (
	"fmt"
	"log"
	"sort"
	"strings"

	"github.com/piprate/json-gold/ld"
)

func main() {
	proc := ld.NewJsonLdProcessor()
	options := ld.NewJsonLdOptions("")
	options.Format = "application/n-quads"

	// this JSON-LD document was taken from http://json-ld.org/test-suite/tests/toRdf-0028-in.jsonld
	doc := map[string]interface{}{
		"@context": map[string]interface{}{
			"sec":        "http://purl.org/security#",
			"xsd":        "http://www.w3.org/2001/XMLSchema#",
			"rdf":        "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
			"dc":         "http://purl.org/dc/terms/",
			"sec:signer": map[string]interface{}{"@type": "@id"},
			"dc:created": map[string]interface{}{"@type": "xsd:dateTime"},
		},
		"@id":                "http://example.org/sig1",
		"@type":              []interface{}{"rdf:Graph", "sec:SignedGraph"},
		"dc:created":         "2011-09-23T20:21:34Z",
		"sec:signer":         "http://payswarm.example.com/i/john/keys/5",
		"sec:signatureValue": "OGQzNGVkMzVm4NTIyZTkZDYMmMzQzNmExMgoYzI43Q3ODIyOWM32NjI=",
		"@graph": map[string]interface{}{
			"@id":      "http://example.org/fact1",
			"dc:title": "Hello World!",
		},
	}
	triples, err := proc.ToRDF(doc, options)
	if err != nil {
		log.Println("Error running ToRDF:", err)
		return
	}

	temp := strings.Split(triples.(string), "\n")
	sort.Strings(temp)
	triples = strings.Join(temp, "\n")

	fmt.Printf("%s\n", triples)

}
Output:

<http://example.org/fact1> <http://purl.org/dc/terms/title> "Hello World!" <http://example.org/sig1> .
<http://example.org/sig1> <http://purl.org/dc/terms/created> "2011-09-23T20:21:34Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
<http://example.org/sig1> <http://purl.org/security#signatureValue> "OGQzNGVkMzVm4NTIyZTkZDYMmMzQzNmExMgoYzI43Q3ODIyOWM32NjI=" .
<http://example.org/sig1> <http://purl.org/security#signer> <http://payswarm.example.com/i/john/keys/5> .
<http://example.org/sig1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://purl.org/security#SignedGraph> .
<http://example.org/sig1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/1999/02/22-rdf-syntax-ns#Graph> .

type JsonLdUrl

type JsonLdUrl struct {
	Href      string
	Protocol  string
	Host      string
	Auth      string
	User      string
	Password  string
	Hostname  string
	Port      string
	Relative  string
	Path      string
	Directory string
	File      string
	Query     string
	Hash      string

	// things not populated by the regex
	Pathname       string
	NormalizedPath string
	Authority      string
}

JsonLdUrl represents a URL split into individual components for easy manipulation. TODO: This implementation was taken from Java. Do we really need it in Go?

func ParseURL

func ParseURL(url string) *JsonLdUrl

ParseURL parses a string URL into JsonLdUrl struct.

type Literal

type Literal struct {
	Value    string
	Datatype string
	Language string
}

Literal represents a literal value.

func NewLiteral

func NewLiteral(value string, datatype string, language string) *Literal

NewLiteral creates a new instance of Literal.

func (Literal) Equal

func (l Literal) Equal(n Node) bool

Equal returns true id this node is equal to the given node.

func (Literal) GetValue

func (l Literal) GetValue() string

GetValue returns the node's value.

type NQuadRDFSerializer

type NQuadRDFSerializer struct {
}

NQuadRDFSerializer parses and serializes N-Quads.

func (*NQuadRDFSerializer) Parse

func (s *NQuadRDFSerializer) Parse(input interface{}) (*RDFDataset, error)

Parse N-Quads from string into an RDFDataset.

func (*NQuadRDFSerializer) Serialize

func (s *NQuadRDFSerializer) Serialize(dataset *RDFDataset) (interface{}, error)

Serialize an RDFDataset into N-Quad string.

func (*NQuadRDFSerializer) SerializeTo

func (s *NQuadRDFSerializer) SerializeTo(w io.Writer, dataset *RDFDataset) error

SerializeTo writes RDFDataset as N-Quad into a writer.

type Node

type Node interface {
	// GetValue returns the node's value.
	GetValue() string

	// Equal returns true id this node is equal to the given node.
	Equal(n Node) bool
}

Node is the value of a subject, predicate or object i.e. a IRI reference, blank node or literal.

type NodeMapNode

type NodeMapNode struct {
	Values map[string]interface{}
	// contains filtered or unexported fields
}

NodeMapNode

func NewNodeMapNode

func NewNodeMapNode(id string) *NodeMapNode

NewNodeMapNode creates a new instance of NodeMapNode.

func (*NodeMapNode) IsWellFormedListNode

func (nmn *NodeMapNode) IsWellFormedListNode() bool

IsWellFormedListNode is a helper function for 4.3.3

func (*NodeMapNode) Serialize

func (nmn *NodeMapNode) Serialize() map[string]interface{}

Serialize returns this node without the usages variable

type NormalisationAlgorithm

type NormalisationAlgorithm struct {
	// contains filtered or unexported fields
}

func NewNormalisationAlgorithm

func NewNormalisationAlgorithm(version string) *NormalisationAlgorithm

func (*NormalisationAlgorithm) Main

func (na *NormalisationAlgorithm) Main(dataset *RDFDataset, opts *JsonLdOptions) (interface{}, error)

type Permutator

type Permutator struct {
	// contains filtered or unexported fields
}

Permutator

func NewPermutator

func NewPermutator(list []string) *Permutator

NewPermutator creates a new instance of Permutator.

func (*Permutator) HasNext

func (p *Permutator) HasNext() bool

HasNext returns true if there is another permutation.

func (*Permutator) Next

func (p *Permutator) Next() []string

Next gets the next permutation. Call HasNext() to ensure there is another one first.

type Quad

type Quad struct {
	Subject   Node
	Predicate Node
	Object    Node
	Graph     Node
}

Quad represents an RDF quad.

func NewQuad

func NewQuad(subject Node, predicate Node, object Node, graph string) *Quad

NewQuad creates a new instance of Quad.

func (Quad) Equal

func (q Quad) Equal(o *Quad) bool

Equal returns true if this quad is equal to the given quad.

func (Quad) Valid added in v0.3.0

func (q Quad) Valid() bool

type RDFDataset

type RDFDataset struct {
	Graphs map[string][]*Quad
	// contains filtered or unexported fields
}

RDFDataset is an internal representation of an RDF dataset.

func NewRDFDataset

func NewRDFDataset() *RDFDataset

NewRDFDataset creates a new instance of RDFDataset.

func ParseNQuads

func ParseNQuads(input string) (*RDFDataset, error)

ParseNQuads parses RDF in the form of N-Quads.

func ParseNQuadsFrom

func ParseNQuadsFrom(o interface{}) (*RDFDataset, error)

ParseNQuadsFrom parses RDF in the form of N-Quads from io.Reader, []byte or string.

func (*RDFDataset) ClearNamespaces

func (ds *RDFDataset) ClearNamespaces()

ClearNamespaces clears all the namespaces in this dataset

func (*RDFDataset) GetContext

func (ds *RDFDataset) GetContext() map[string]interface{}

GetContext returns a valid context containing any namespaces set.

func (*RDFDataset) GetNamespace

func (ds *RDFDataset) GetNamespace(ns string) string

GetNamespace

func (*RDFDataset) GetNamespaces

func (ds *RDFDataset) GetNamespaces() map[string]string

GetNamespaces

func (*RDFDataset) GetQuads

func (ds *RDFDataset) GetQuads(graphName string) []*Quad

GetQuads returns a list of quads for the given graph

func (*RDFDataset) GraphToRDF

func (ds *RDFDataset) GraphToRDF(graphName string, graph map[string]interface{}, issuer *IdentifierIssuer,
	produceGeneralizedRdf bool)

GraphToRDF creates an array of RDF triples for the given graph.

func (*RDFDataset) ParseContext

func (ds *RDFDataset) ParseContext(contextLike interface{}, opts *JsonLdOptions) error

ParseContext parses a context object and sets any namespaces found within it.

func (*RDFDataset) SetNamespace

func (ds *RDFDataset) SetNamespace(ns string, prefix string)

SetNamespace

type RDFSerializer

type RDFSerializer interface {
	// Parse the input into the internal RDF Dataset format.
	// The format is a map with the following structure:
	// {
	// 	   GRAPH_1: [ TRIPLE_1, TRIPLE_2, ..., TRIPLE_N ],
	//     GRAPH_2: [ TRIPLE_1, TRIPLE_2, ..., TRIPLE_N ],
	//     ...
	//     GRAPH_N: [ TRIPLE_1, TRIPLE_2, ..., TRIPLE_N ]
	// }
	//
	// GRAPH: Must be the graph name/IRI. If no graph is present for a triple,
	// add it to the "@default" graph TRIPLE: Must be a map with the following
	// structure:
	// {
	//     "subject" : SUBJECT,
	//     "predicate" : PREDICATE,
	//     "object" : OBJECT
	// }
	//
	// Each of the values in the triple map must also be a map with the
	// following key-value pairs:
	//
	// "value": The value of the node.
	// "subject" can be an IRI or blank node id.
	// "predicate" should only ever be an IRI
	// "object" can be and IRI or blank node id, or a literal value (represented
	//     as a string)
	// "type": "IRI" if the value is an IRI or "blank node" if the
	// value is a blank node. "object" can also be "literal" in the case of
	// literals. The value of "object" can also contain the following optional
	// key-value pairs:
	//
	// "language" : the language value of a string literal
	// "datatype" : the datatype of the literal. (if not set will default to XSD:string,
	//     if set to null, null will be used).
	//
	Parse(input interface{}) (*RDFDataset, error)

	// Serialize an RDFDataset
	Serialize(dataset *RDFDataset) (interface{}, error)
}

RDFSerializer can serialize and de-serialize RDFDatasets.

type RDFSerializerTo

type RDFSerializerTo interface {
	SerializeTo(w io.Writer, dataset *RDFDataset) error
}

RDFSerializerTo can serialize RDFDatasets into io.Writer.

type RFC7324CachingDocumentLoader added in v0.1.1

type RFC7324CachingDocumentLoader struct {
	// contains filtered or unexported fields
}

RFC7324CachingDocumentLoader respects RFC7324 caching headers in order to cache effectively

func NewRFC7324CachingDocumentLoader added in v0.1.1

func NewRFC7324CachingDocumentLoader(httpClient *http.Client) *RFC7324CachingDocumentLoader

NewRFC7324CachingDocumentLoader creates a new RFC7324CachingDocumentLoader

func (*RFC7324CachingDocumentLoader) LoadDocument added in v0.1.1

func (rcdl *RFC7324CachingDocumentLoader) LoadDocument(u string) (*RemoteDocument, error)

LoadDocument returns a RemoteDocument containing the contents of the JSON resource from the given URL.

type RemoteDocument

type RemoteDocument struct {
	DocumentURL string
	Document    interface{}
	ContextURL  string
}

RemoteDocument is a document retrieved from a remote source.

type ShortestLeast

type ShortestLeast []string

ShortestLeast is a struct which allows sorting using CompareShortestLeast function.

func (ShortestLeast) Len

func (s ShortestLeast) Len() int

func (ShortestLeast) Less

func (s ShortestLeast) Less(i, j int) bool

func (ShortestLeast) Swap

func (s ShortestLeast) Swap(i, j int)

type StackNode added in v0.2.0

type StackNode struct {
	// contains filtered or unexported fields
}

type TurtleRDFSerializer

type TurtleRDFSerializer struct {
}

TurtleRDFSerializer parses and serializes Turtle data.

func (*TurtleRDFSerializer) Parse

func (s *TurtleRDFSerializer) Parse(input interface{}) (*RDFDataset, error)

Parse Turtle from string into an RDFDataset

func (*TurtleRDFSerializer) Serialize

func (s *TurtleRDFSerializer) Serialize(dataset *RDFDataset) (interface{}, error)

Serialize an RDFDataset into a Turtle string.

type UsagesNode

type UsagesNode struct {
	// contains filtered or unexported fields
}

UsagesNode is a helper class for node usages

func NewUsagesNode

func NewUsagesNode(node *NodeMapNode, property string, value map[string]interface{}) *UsagesNode

NewUsagesNode creates a new instance of UsagesNode

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL