or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-processing.mddocument-loading.mdindex.mdjson-canonicalization.mdrdf-conversion.mdurl-utilities.md

rdf-conversion.mddocs/

0

# RDF Conversion

1

2

Bidirectional conversion between JSON-LD and RDF dataset formats, enabling interoperability with RDF triple stores, semantic web applications, and other RDF-based tools.

3

4

## Capabilities

5

6

### JSON-LD to RDF Conversion

7

8

Converts JSON-LD documents to RDF dataset format, extracting semantic triples and enabling integration with RDF processing systems.

9

10

```python { .api }

11

def to_rdf(input_, options=None):

12

"""

13

Converts JSON-LD document to RDF dataset.

14

15

Args:

16

input_: The JSON-LD document to convert (dict, list, or str)

17

options: Optional conversion settings (dict)

18

19

Options:

20

base (str): The base IRI to use for resolving relative IRIs

21

format (str): Output format ('application/n-quads' for N-Quads string)

22

produceGeneralizedRdf (bool): True to output generalized RDF with

23

non-standard features (default: False)

24

extractAllScripts (bool): True to extract all JSON-LD script elements

25

from HTML (default: True)

26

processingMode (str): JSON-LD processing mode ('json-ld-1.0' or

27

'json-ld-1.1', default: 'json-ld-1.1')

28

documentLoader (function): Custom document loader function

29

30

Returns:

31

dict or str: RDF dataset dict, or N-Quads string if format specified

32

33

Raises:

34

JsonLdError: If conversion fails due to invalid JSON-LD input

35

"""

36

```

37

38

#### Example

39

40

```python

41

from pyld import jsonld

42

43

doc = {

44

"@context": {

45

"name": "http://schema.org/name",

46

"Person": "http://schema.org/Person"

47

},

48

"@id": "http://example.org/person/1",

49

"@type": "Person",

50

"name": "Alice"

51

}

52

53

# Convert to RDF dataset

54

rdf_dataset = jsonld.to_rdf(doc)

55

56

# Convert to N-Quads format

57

nquads = jsonld.to_rdf(doc, {'format': 'application/n-quads'})

58

print(nquads)

59

# Output: <http://example.org/person/1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .

60

# <http://example.org/person/1> <http://schema.org/name> "Alice" .

61

```

62

63

### RDF to JSON-LD Conversion

64

65

Converts RDF datasets or serialized RDF strings to JSON-LD format, enabling JSON-based processing of RDF data.

66

67

```python { .api }

68

def from_rdf(input_, options=None):

69

"""

70

Converts RDF dataset to JSON-LD document.

71

72

Args:

73

input_: RDF dataset dict or serialized RDF string to convert

74

options: Optional conversion settings (dict)

75

76

Options:

77

format (str): Input format when input is string ('application/n-quads'

78

for N-Quads, default: 'application/n-quads')

79

useRdfType (bool): True to use rdf:type, False to use @type

80

(default: False)

81

useNativeTypes (bool): True to convert XSD types to native Python types

82

(bool, int, float), False to keep as strings

83

(default: True)

84

85

Returns:

86

list: JSON-LD document as expanded array

87

88

Raises:

89

JsonLdError: If conversion fails due to invalid RDF input

90

"""

91

```

92

93

#### Example

94

95

```python

96

from pyld import jsonld

97

98

# N-Quads string input

99

nquads = '''

100

<http://example.org/person/1> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Person> .

101

<http://example.org/person/1> <http://schema.org/name> "Alice" .

102

'''

103

104

# Convert from N-Quads to JSON-LD

105

json_ld = jsonld.from_rdf(nquads)

106

print(json_ld)

107

# Output: [{"@id": "http://example.org/person/1", "@type": ["http://schema.org/Person"], "http://schema.org/name": [{"@value": "Alice"}]}]

108

109

# Convert with native types

110

json_ld_native = jsonld.from_rdf(nquads, {'useNativeTypes': True})

111

112

# Use rdf:type instead of @type

113

json_ld_rdf_type = jsonld.from_rdf(nquads, {'useRdfType': True})

114

```

115

116

### RDF Dataset Structure

117

118

When working with RDF datasets (not serialized strings), PyLD uses this internal structure:

119

120

```python { .api }

121

# RDF Dataset format

122

{

123

"@default": [ # Default graph triples

124

{

125

"subject": {"@id": "http://example.org/subject"},

126

"predicate": {"@id": "http://example.org/predicate"},

127

"object": {"@value": "literal value", "@type": "http://www.w3.org/2001/XMLSchema#string"}

128

}

129

],

130

"http://example.org/graph": [ # Named graph triples

131

# ... triples in named graph

132

]

133

}

134

135

# RDF Triple format

136

{

137

"subject": {"@id": "http://example.org/subject"}, # IRI or blank node

138

"predicate": {"@id": "http://example.org/predicate"}, # IRI only

139

"object": { # IRI, blank node, or literal

140

"@id": "http://example.org/object" # For IRI/blank node

141

# OR

142

"@value": "literal value", # For literals

143

"@type": "http://www.w3.org/2001/XMLSchema#string", # Optional datatype

144

"@language": "en" # Optional language tag

145

}

146

}

147

```

148

149

## Conversion Options

150

151

### to_rdf() Options

152

153

- **format**: When set to 'application/n-quads', returns N-Quads string instead of dataset object

154

- **produceGeneralizedRdf**: Allows non-standard RDF features like literals as subjects

155

- **base**: Base IRI for resolving relative references

156

- **extractAllScripts**: Extract all JSON-LD from HTML documents

157

- **processingMode**: JSON-LD version compatibility mode

158

159

### from_rdf() Options

160

161

- **format**: Input serialization format (currently supports 'application/n-quads')

162

- **useRdfType**: Keep rdf:type as property instead of converting to @type

163

- **useNativeTypes**: Convert XSD datatypes to Python native types

164

165

## RDF Parser Registration

166

167

PyLD supports pluggable RDF parsers for different serialization formats:

168

169

```python { .api }

170

def register_rdf_parser(content_type, parser):

171

"""

172

Register a custom RDF parser for a content type.

173

174

Args:

175

content_type (str): MIME type to associate with parser

176

parser (function): Parser function that takes RDF string and returns dataset

177

"""

178

179

def unregister_rdf_parser(content_type):

180

"""

181

Unregister an RDF parser for a content type.

182

183

Args:

184

content_type (str): MIME type to unregister

185

"""

186

```

187

188

#### Example

189

190

```python

191

from pyld import jsonld

192

193

def custom_turtle_parser(rdf_string):

194

# Custom parser implementation

195

# Must return RDF dataset in PyLD format

196

pass

197

198

# Register parser

199

jsonld.register_rdf_parser('text/turtle', custom_turtle_parser)

200

201

# Use with from_rdf

202

turtle_data = "@prefix ex: <http://example.org/> . ex:subject ex:predicate ex:object ."

203

json_ld = jsonld.from_rdf(turtle_data, {'format': 'text/turtle'})

204

```

205

206

## Data Type Mapping

207

208

### XSD to Python Type Conversion

209

210

When `useNativeTypes` is True, XSD datatypes are converted to Python types:

211

212

| XSD Type | Python Type | Example |

213

|----------|-------------|---------|

214

| `xsd:boolean` | `bool` | `true``True` |

215

| `xsd:integer` | `int` | `"42"``42` |

216

| `xsd:double` | `float` | `"3.14"``3.14` |

217

| `xsd:string` | `str` | `"hello"``"hello"` |

218

219

### Blank Node Handling

220

221

Blank nodes are represented with special @id values:

222

223

```python

224

# Blank node in RDF dataset

225

{

226

"subject": {"@id": "_:b0"}, # Blank node identifier

227

"predicate": {"@id": "http://example.org/predicate"},

228

"object": {"@value": "value"}

229

}

230

```

231

232

## Error Handling

233

234

RDF conversion functions may raise `JsonLdError` with these specific error types:

235

236

- **invalid RDF**: Malformed RDF input

237

- **RDF parsing error**: Parser-specific errors

238

- **invalid JSON-LD**: JSON-LD that cannot be converted to RDF

239

- **loading document failed**: Issues loading remote RDF documents

240

241

## Use Cases

242

243

### Triple Store Integration

244

245

```python

246

# Export JSON-LD to triple store

247

json_ld_doc = {...}

248

nquads = jsonld.to_rdf(json_ld_doc, {'format': 'application/n-quads'})

249

# Store nquads in triple store

250

251

# Import from triple store

252

nquads_from_store = get_nquads_from_triple_store()

253

json_ld = jsonld.from_rdf(nquads_from_store)

254

```

255

256

### Data Pipeline Processing

257

258

```python

259

# Convert between formats in data pipeline

260

def process_semantic_data(input_data, input_format, output_format):

261

if input_format == 'json-ld' and output_format == 'nquads':

262

return jsonld.to_rdf(input_data, {'format': 'application/n-quads'})

263

elif input_format == 'nquads' and output_format == 'json-ld':

264

return jsonld.from_rdf(input_data, {'format': 'application/n-quads'})

265

```