-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonldConverter.js
274 lines (247 loc) · 9.01 KB
/
jsonldConverter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
* Copyright (c) 2023 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict'
const $RefParser = require('json-schema-ref-parser');
var $rdf = require('rdflib');
const fs = require('fs')
const yargs = require('yargs')
const path = require('path')
const N3 = require('n3');
const url = require('url');
const { DataFactory } = N3;
const { namedNode, literal, blankNode, defaultGraph, quad } = DataFactory;
//const { URL } = require('url'); // Import the URL module
const ContextParser = require('jsonld-context-parser').ContextParser;
const ContextUtil = require('jsonld-context-parser').Util;
const myParser = new ContextParser();
const jsonld = require('jsonld');
const exp = require('constants');
const RDF = $rdf.Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#');
const SHACL = $rdf.Namespace('http://www.w3.org/ns/shacl#');
const IFFK = $rdf.Namespace('https://industry-fusion.org/knowledge/v0.1/');
const argv = yargs
.usage('Usage: $0 <json-file> [options]')
.option('concise', {
alias: 'n',
description: 'Create concise/compacted from',
demandOption: false,
type: 'string'
})
.option('expand', {
alias: 'x',
description: 'Create expanded from',
demandOption: false,
type: 'string'
})
.option('normalize', {
alias: 'r',
description: 'Create normalized from',
demandOption: false,
type: 'string'
})
.option('context', {
alias: 'c',
description: 'JSON-LD-Context',
demandOption: false,
type: 'string'
})
.help()
.alias('help', 'h')
.argv
const jsonFileName = argv['_'][0];
const jsonText = fs.readFileSync(jsonFileName, 'utf8');
const jsonObj = JSON.parse(jsonText);
var jsonArr;
if (!(argv.x === undefined) && !(argv.n === undefined)) {
console.error("Expand and Concise are mutally exclusive. Bye!")
process.exit(1)
}
if (!(argv.r === undefined) && !(argv.n === undefined)) {
console.error("Normalized and Concise are mutally exclusive. Bye!")
process.exit(1)
}
if (!(argv.x === undefined) && !(argv.r === undefined)) {
console.error("Normalized and Expanded are mutally exclusive. Bye!")
process.exit(1)
}
if (argv.x === undefined && argv.r === undefined && argv.n === undefined) {
console.error("No processing switch selected. Bye!")
process.exit(1)
}
if (!Array.isArray(jsonObj)){
jsonArr = [jsonObj]
} else {
jsonArr = jsonObj
}
function assertNoContext(jsonObj) {
if (Array.isArray(jsonObj)) {
jsonObj.forEach((obj) => {
if ("@context" in obj) {
console.error("Error: @contex found in json-object. Only fully expanded objects without @context can be compacted. Exiting!");
process.exit(1);
}
})
} else {
if ("@context" in jsonObj) {
console.error("Error: @context found in json-object. Only fully expanded objects without @context can be compacted. Exiting!");
process.exit(1);
}
}
}
// Check if every object in array whether it has Context
function hasContexts(jsonArr) {
jsonArr.forEach(jsonObj => {
if (!("@context" in jsonObj)) {
return false
}
})
return true;
}
function loadContextFromFile(fileName) {
const context = fs.readFileSync(fileName, 'utf8');
const contextParsed = JSON.parse(context)
return contextParsed;
}
// Merge Contexts
function mergeContexts(jsonArr, context) {
function mergeContext(localContext, context) {
var mergedContext = [];
if (Array.isArray(localContext)){
mergedContext = [localContext];
}
if (context === undefined) {
if (mergedContext.length === 0) {
return null;
}
return mergedContext;
} else if (!Array.isArray(context)) {
context = [context];
}
context.forEach(c => {
if (typeof(c) !== "string" || mergedContext.find(x => c === x) === undefined) {
mergedContext.push(c)
}
})
return mergedContext;
}
const parseContextUrl = url.parse(context, true);
if (parseContextUrl.protocol === "file:"){
context = loadContextFromFile(parseContextUrl.path);
}
return jsonArr.map(jsonObj => {
const localContext = jsonObj["@context"]
return mergeContext(localContext, context)
})
}
function conciseExpandedForm(expanded) {
function filterAttribute(attr) {
if (typeof(attr) === 'object') {
if ("@type" in attr && (attr["@type"][0] === 'https://uri.etsi.org/ngsi-ld/Property' ||
attr["@type"][0] === "https://uri.etsi.org/ngsi-ld/Relationship")) {
delete attr["@type"];
}
if ("https://uri.etsi.org/ngsi-ld/hasValue" in attr) {
attr["@value"] = attr["https://uri.etsi.org/ngsi-ld/hasValue"][0]["@value"]
delete attr["https://uri.etsi.org/ngsi-ld/hasValue"];
}
}
}
expanded.forEach(c => {
Object.keys(c).forEach(key => {
if (Array.isArray(c[key])) {
c[key].forEach(a => filterAttribute(a))
} else {
filterAttribute(c[key])
}
})
})
return expanded;
}
function normalizeExpandedForm(expanded) {
function extendAttribute(attr) {
if (typeof(attr) === 'object') {
if (!("@type" in attr)) {
if ("https://uri.etsi.org/ngsi-ld/hasValue" in attr || "@value" in attr || "@id" in attr) {
attr["@type"] = "https://uri.etsi.org/ngsi-ld/Property"
} else if ("https://uri.etsi.org/ngsi-ld/hasObject" in attr) {
attr["@type"] = "https://uri.etsi.org/ngsi-ld/Relationship"
}
if ("@value" in attr) {
attr["https://uri.etsi.org/ngsi-ld/hasValue"] = attr["@value"]
delete attr["@value"]
} else if ("@id" in attr) {
attr["https://uri.etsi.org/ngsi-ld/hasValue"] = {"@id": attr["@id"]}
delete attr["@id"]
}
}
}
}
expanded.forEach(c => {
Object.keys(c).forEach(key => {
if (Array.isArray(c[key])) {
c[key].forEach(a => extendAttribute(a))
} else {
extendAttribute(c[key])
}
})
})
return expanded;
}
async function expand(objArr, contextArr) {
const expanded = await Promise.all(objArr.map(async(jsonObj, index) => {
jsonObj['@context'] = contextArr[index];
var res = await jsonld.expand(jsonObj)
return res[0];
}));
return expanded;
}
async function compact(objArr, contextArr) {
return await Promise.all(objArr.map(async(jsonObj, index) => jsonld.compact(jsonObj, contextArr[index])));
}
(async (jsonArr) => {
if (!(argv.n === undefined)) {
const mergedContexts = mergeContexts(jsonArr, argv.c);
if (mergedContexts !== undefined && mergedContexts.find(x => x === null)) {
console.error("Error: For Compaction, context must be either defined in all objects or externally. Exiting!");
process.exit(1);
}
// Compaction to find Properties in compacted form
const expanded = await expand(jsonArr, mergedContexts);
const concised = conciseExpandedForm(expanded);
const compacted = await compact(concised, mergedContexts);
console.log(JSON.stringify(compacted, null, 2));
}
if (!(argv.x === undefined)) {
const mergedContexts = mergeContexts(jsonArr, argv.c);
if (mergedContexts !== undefined && mergedContexts.find(x => x === null)) {
console.error("Error: For Extraction, context must be either defined in all objects or externally. Exiting!");
process.exit(1);
}
const expanded = await expand(jsonArr, mergedContexts);
console.log(JSON.stringify(expanded, null, 2));
}
if (!(argv.r === undefined)) {
const mergedContexts = mergeContexts(jsonArr, argv.c);
if (mergedContexts !== undefined && mergedContexts.find(x => x === null)) {
console.error("Error: For Normalization, context must be either defined in all objects or externally. Exiting!");
process.exit(1);
}
const expanded = await expand(jsonArr, mergedContexts);
const normalized = normalizeExpandedForm(expanded);
const compacted = await compact(normalized, mergedContexts);
console.log(JSON.stringify(compacted, null, 2));
}
})(jsonArr)