@terzogenito/json-utils 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +250 -3
  2. package/index.js +399 -1
  3. package/package.json +11 -4
package/README.md CHANGED
@@ -3,6 +3,19 @@
3
3
  ## Overview
4
4
  This module provides various functions for reading, validating, and processing JSON files and URL content.
5
5
 
6
+ ## Installation
7
+ ```bash
8
+ npm install @terzogenito/json-utils
9
+ ```
10
+
11
+ ## Quick Start
12
+ ```javascript
13
+ import jsonUtils from '@terzogenito/json-utils';
14
+
15
+ const jsonAttributes = jsonUtils.getAttributes(jsonData);
16
+ console.log(jsonAttributes);
17
+ ```
18
+
6
19
  ## Function List
7
20
 
8
21
  ### 1. `getData(path)`
@@ -182,9 +195,243 @@ app.getJSON("https://api.example.com/data", jsonData => {
182
195
  });
183
196
  ```
184
197
 
185
- ## Installation
186
- ```bash
187
- npm install @terzogenito/json-utils
198
+ ### 13. getAttributes(jsonObject)
199
+ ```javascript
200
+ const dataJSON = app.readJSON(data);
201
+ const attributes = app.getAttributes(dataJSON);
202
+ // Output: ['name', 'age', 'isActive', 'address', 'hobbies']
203
+ ```
204
+
205
+ **Description**: Extracts all attribute/keys from a JSON object and returns them as an array.
206
+
207
+ **Parameters**:
208
+ - jsonObject (Object|String): JSON object or JSON string
209
+
210
+ Returns: Array of attribute names
211
+
212
+ ### 14. getMeta(jsonObject)
213
+ ```javascript
214
+ const meta = app.getMeta(dataJSON);
215
+ // Output: {"name": "string", "age": "integer", "isActive": "boolean"}
216
+ ```
217
+
218
+ **Description**: Generates metadata showing attribute names and their data types.
219
+
220
+ **Parameters**:
221
+ - jsonObject (Object|String): JSON object or JSON string
222
+
223
+ Returns: Object with attribute names as keys and data types as values
224
+
225
+ Data Types Identified:
226
+ - string, integer, float, boolean, array, object, null, date
227
+
228
+ ### 15. getMetaDetail(jsonObject)
229
+ ```javascript
230
+ const metaDetail = app.getMetaDetail(dataJSON);
231
+ // Output: Detailed metadata including nested structures
232
+ ```
233
+
234
+ **Description**: Generates comprehensive metadata including nested attributes, data types, paths, and structural information.
235
+
236
+ **Parameters**:
237
+ - jsonObject (Object|String): JSON object or JSON string
238
+
239
+ Returns: Object with detailed metadata for each attribute
240
+
241
+ Metadata Includes:
242
+ - type: Data type
243
+ - isRequired: Whether attribute exists
244
+ - path: Full path to attribute
245
+ - children: Nested attributes (for objects)
246
+ - length: Array length (for arrays)
247
+ - elementType: Type of array elements
248
+
249
+ ### 16. getMetaCompact(jsonObject)
250
+ ```javascript
251
+ const metaCompact = app.getMetaCompact(dataJSON);
252
+ // Output: Compact metadata format
253
+ ```
254
+
255
+ **Description**: Creates a compact metadata representation showing the structure hierarchy.
256
+
257
+ **Parameters**:
258
+ - jsonObject (Object|String): JSON object or JSON string
259
+
260
+ Returns: Compact representation of JSON structure
261
+
262
+ Format Examples:
263
+ - "array[string]": Array of strings
264
+ - "array[object]": Array of objects
265
+ - Nested objects shown as nested objects
266
+
267
+ ### 17. getPartial(jsonObject, attributes)
268
+ ```javascript
269
+ const partial = app.getPartial(dataJSON, ["name", "age"]);
270
+ // Output: {"name": "John", "age": 30}
271
+ ```
272
+
273
+ **Description**: Extracts specific attributes from a JSON object.
274
+
275
+ **Parameters**:
276
+ - jsonObject (Object|String): JSON object or JSON string
277
+ - attributes (Array|String|Object): Attributes to extract
278
+
279
+ attribute Parameter Types:
280
+ - Array: List of attribute names to extract
281
+ ```javascript
282
+ app.getPartial(data, ["name", "age"])
283
+ ```
284
+ - String: Single attribute name
285
+ ```javascript
286
+ app.getPartial(data, "name")
287
+ ```
288
+ - Object: Mapping of new names to original attributes
289
+ ```javascript
290
+ app.getPartial(data, {"fullName": "name", "yearsOld": "age"})
291
+ ```
292
+
293
+ Returns: Object containing only the specified attributes
294
+
295
+ ### 18. getPartialDeep(jsonObject, attributePaths)
296
+ ```javascript
297
+ const deepPartial = app.getPartialDeep(dataJSON, ["name", "address.city", "hobbies.length"]);
298
+ // Output: {"name": "John", "city": "Jakarta", "length": 2}
299
+ ```
300
+
301
+ **Description**: Extracts attributes using nested paths (dot notation).
302
+
303
+ **Parameters**:
304
+ - jsonObject (Object|String): JSON object or JSON string
305
+ - attributePaths (Array|Object): Paths to extract
306
+
307
+ attributePaths Parameter Types:
308
+ - Array: List of dot-notated paths
309
+ ```javascript
310
+ app.getPartialDeep(data, ["user.profile.name", "user.contact.email"])
311
+ ```
312
+ - Object: Mapping of new names to paths
313
+ ```javascript
314
+ app.getPartialDeep(data, {"userName": "user.profile.name", "userEmail": "user.contact.email"})
315
+ ```
316
+
317
+ Returns: Object with extracted values (uses last path segment as key for array input)
318
+
319
+ ### 19. getPartialWithDefaults(jsonObject, attributesConfig)
320
+ ```javascript
321
+ const partialWithDefaults = app.getPartialWithDefaults(dataJSON, {
322
+ "name": "name",
323
+ "status": {
324
+ path: "isActive",
325
+ transform: (val) => val ? "Active" : "Inactive"
326
+ },
327
+ "email": {
328
+ path: "contact.email",
329
+ default: "no-email@example.com"
330
+ }
331
+ });
332
+ ```
333
+
334
+ **Description**: Extracts attributes with advanced configuration including default values and transformations.
335
+
336
+ **Parameters**:
337
+ - jsonObject (Object|String): JSON object or JSON string
338
+ - attributesConfig (Object): Configuration object
339
+
340
+ Configuration Options:
341
+ - String: Simple path extraction
342
+ ```javascript
343
+ "name": "user.fullName"
344
+ ```
345
+ - Object: Advanced configuration
346
+ ```javascript
347
+ "formattedAge": {
348
+ path: "age", // Required: Path to attribute
349
+ default: 0, // Optional: Default value if path doesn't exist
350
+ transform: (val) => ${val} years old // Optional: Transformation function
351
+ }
352
+ ```
353
+
354
+ Returns: Object with extracted and processed values
355
+
356
+ ### 20. excludeAttributes(jsonObject, attributesToExclude)
357
+ ```javascript
358
+ const filtered = app.excludeAttributes(dataJSON, ["isActive", "address"]);
359
+ // Output: {"name": "John", "age": 30, "hobbies": ["reading", "coding"]}
360
+ ```
361
+
362
+ **Description**: Creates a new JSON object excluding specified attributes.
363
+
364
+ **Parameters**:
365
+ - jsonObject (Object|String): JSON object or JSON string
366
+ - attributesToExclude (Array|String): Attributes to remove
367
+
368
+ attributesToExclude Parameter Types:
369
+ - Array: List of attribute names to exclude
370
+ ```javascript
371
+ app.excludeAttributes(data, ["password", "secretKey"])
372
+ ```
373
+ - String: Single attribute name to exclude
374
+ ```javascript
375
+ app.excludeAttributes(data, "password")
376
+ ```
377
+
378
+ Returns: New object without the excluded attributes
379
+
380
+ ### 21. getAttributeValue(jsonObject, attributeName, defaultValue)
381
+ ```javascript
382
+ const name = app.getAttributeValue(dataJSON, "name");
383
+ const email = app.getAttributeValue(dataJSON, "email", "default@email.com");
384
+ ```
385
+
386
+ **Description**: Gets the value of a specific attribute with optional default value.
387
+
388
+ **Parameters**:
389
+ - jsonObject (Object|String): JSON object or JSON string
390
+ - attributeName (String): Name of the attribute to retrieve
391
+ - defaultValue (Any, optional): Default value if attribute doesn't exist
392
+
393
+ Returns: Attribute value or default value
394
+
395
+ Advanced Usage Examples
396
+ ```javascript
397
+ const app = require('./index');
398
+
399
+ // Get all attributes from JSON
400
+ const data = await app.getData('./data.json');
401
+ const jsonData = app.readJSON(data);
402
+ const attributes = app.getAttributes(jsonData);
403
+
404
+ // Get metadata information
405
+ const meta = app.getMeta(jsonData);
406
+ const metaDetail = app.getMetaDetail(jsonData);
407
+
408
+ // Extract specific data
409
+ const userInfo = app.getPartial(jsonData, ["name", "email", "phone"]);
410
+ const nestedData = app.getPartialDeep(jsonData, ["user.profile.name", "user.contact.email"]);
411
+
412
+ // Extract with transformations and defaults
413
+ const processedData = app.getPartialWithDefaults(jsonData, {
414
+ "fullName": "user.name",
415
+ "ageFormatted": {
416
+ path: "user.age",
417
+ transform: (age) => ${age} years old
418
+ },
419
+ "country": {
420
+ path: "user.address.country",
421
+ default: "Unknown"
422
+ }
423
+ });
424
+
425
+ // Exclude sensitive information
426
+ const safeData = app.excludeAttributes(jsonData, ["password", "ssn", "creditCard"]);
427
+
428
+ // Analyze complex nested structures
429
+ const complexMeta = app.getMetaDetail(complexJSON);
430
+ console.log(complexMeta.user?.children?.contact?.children?.email?.type); // "string"
431
+
432
+ // Get single attribute value
433
+ const userName = app.getAttributeValue(jsonData, "name");
434
+ const userEmail = app.getAttributeValue(jsonData, "email", "no-email@example.com");
188
435
  ```
189
436
 
190
437
  ## Requirements
package/index.js CHANGED
@@ -132,6 +132,394 @@ function beautify(jsonObject, indent) {
132
132
  }
133
133
  }
134
134
 
135
+ function getAttributes(jsonObject) {
136
+ try {
137
+ if (typeof jsonObject === 'string') {
138
+ jsonObject = JSON.parse(jsonObject);
139
+ }
140
+
141
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
142
+ return [];
143
+ }
144
+
145
+ return Object.keys(jsonObject);
146
+ } catch (error) {
147
+ return [];
148
+ }
149
+ }
150
+
151
+ function getMeta(jsonObject) {
152
+ try {
153
+ if (typeof jsonObject === 'string') {
154
+ jsonObject = JSON.parse(jsonObject);
155
+ }
156
+
157
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
158
+ return {};
159
+ }
160
+
161
+ const meta = {};
162
+
163
+ for (const [key, value] of Object.entries(jsonObject)) {
164
+ let type = typeof value;
165
+
166
+ if (type === 'object') {
167
+ if (value === null) {
168
+ type = 'null';
169
+ } else if (Array.isArray(value)) {
170
+ type = 'array';
171
+ } else if (value instanceof Date) {
172
+ type = 'date';
173
+ } else {
174
+ type = 'object';
175
+ }
176
+ } else if (type === 'number') {
177
+ type = Number.isInteger(value) ? 'integer' : 'float';
178
+ }
179
+
180
+ meta[key] = type;
181
+ }
182
+
183
+ return meta;
184
+ } catch (error) {
185
+ return {};
186
+ }
187
+ }
188
+
189
+ function getMetaDetail(jsonObject) {
190
+ try {
191
+ if (typeof jsonObject === 'string') {
192
+ jsonObject = JSON.parse(jsonObject);
193
+ }
194
+
195
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
196
+ return {};
197
+ }
198
+
199
+ function getNestedMeta(obj, path = '') {
200
+ const meta = {};
201
+
202
+ for (const [key, value] of Object.entries(obj)) {
203
+ const currentPath = path ? `${path}.${key}` : key;
204
+ const attributeMeta = {};
205
+
206
+ let type = typeof value;
207
+
208
+ if (value === null) {
209
+ type = 'null';
210
+ attributeMeta.type = type;
211
+ attributeMeta.isRequired = false;
212
+ attributeMeta.path = currentPath;
213
+ } else if (Array.isArray(value)) {
214
+ type = 'array';
215
+ attributeMeta.type = type;
216
+ attributeMeta.length = value.length;
217
+ attributeMeta.isRequired = true;
218
+ attributeMeta.path = currentPath;
219
+
220
+ if (value.length > 0) {
221
+ const firstElement = value[0];
222
+ const elementType = typeof firstElement;
223
+
224
+ if (elementType === 'object' && firstElement !== null) {
225
+ if (Array.isArray(firstElement)) {
226
+ attributeMeta.elementType = 'array';
227
+ } else {
228
+ attributeMeta.elementType = 'object';
229
+ attributeMeta.children = getNestedMeta(firstElement, `${currentPath}[0]`);
230
+ }
231
+ } else {
232
+ attributeMeta.elementType = elementType;
233
+ }
234
+ } else {
235
+ attributeMeta.elementType = 'unknown';
236
+ }
237
+ } else if (value instanceof Date) {
238
+ type = 'date';
239
+ attributeMeta.type = type;
240
+ attributeMeta.isRequired = true;
241
+ attributeMeta.path = currentPath;
242
+ } else if (type === 'object') {
243
+ type = 'object';
244
+ attributeMeta.type = type;
245
+ attributeMeta.isRequired = true;
246
+ attributeMeta.path = currentPath;
247
+ attributeMeta.keysCount = Object.keys(value).length;
248
+
249
+ attributeMeta.children = getNestedMeta(value, currentPath);
250
+ } else {
251
+ attributeMeta.type = type;
252
+ attributeMeta.isRequired = true;
253
+ attributeMeta.path = currentPath;
254
+
255
+ if (type === 'number') {
256
+ attributeMeta.numberType = Number.isInteger(value) ? 'integer' : 'float';
257
+ }
258
+ }
259
+
260
+ meta[key] = attributeMeta;
261
+ }
262
+
263
+ return meta;
264
+ }
265
+
266
+ return getNestedMeta(jsonObject);
267
+ } catch (error) {
268
+ console.error('Error in getMetaDetail:', error);
269
+ return {};
270
+ }
271
+ }
272
+
273
+ function getMetaCompact(jsonObject) {
274
+ try {
275
+ if (typeof jsonObject === 'string') {
276
+ jsonObject = JSON.parse(jsonObject);
277
+ }
278
+
279
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
280
+ return {};
281
+ }
282
+
283
+ function getCompactMeta(obj) {
284
+ const meta = {};
285
+
286
+ for (const [key, value] of Object.entries(obj)) {
287
+ let type = typeof value;
288
+
289
+ if (value === null) {
290
+ meta[key] = 'null';
291
+ } else if (Array.isArray(value)) {
292
+ if (value.length > 0) {
293
+ const firstElement = value[0];
294
+ const elementType = typeof firstElement;
295
+ if (elementType === 'object' && firstElement !== null) {
296
+ meta[key] = `array[${Array.isArray(firstElement) ? 'array' : 'object'}]`;
297
+ } else {
298
+ meta[key] = `array[${elementType}]`;
299
+ }
300
+ } else {
301
+ meta[key] = 'array[]';
302
+ }
303
+ } else if (value instanceof Date) {
304
+ meta[key] = 'date';
305
+ } else if (type === 'object') {
306
+ meta[key] = getCompactMeta(value);
307
+ } else if (type === 'number') {
308
+ meta[key] = Number.isInteger(value) ? 'integer' : 'float';
309
+ } else {
310
+ meta[key] = type;
311
+ }
312
+ }
313
+
314
+ return meta;
315
+ }
316
+
317
+ return getCompactMeta(jsonObject);
318
+ } catch (error) {
319
+ console.error('Error in getMetaCompact:', error);
320
+ return {};
321
+ }
322
+ }
323
+
324
+ function getPartial(jsonObject, attributes) {
325
+ try {
326
+ if (typeof jsonObject === 'string') {
327
+ jsonObject = JSON.parse(jsonObject);
328
+ }
329
+
330
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
331
+ return {};
332
+ }
333
+
334
+ const result = {};
335
+
336
+ if (Array.isArray(attributes)) {
337
+ for (const attr of attributes) {
338
+ if (attr in jsonObject) {
339
+ result[attr] = jsonObject[attr];
340
+ }
341
+ }
342
+ }
343
+ else if (typeof attributes === 'string') {
344
+ if (attributes in jsonObject) {
345
+ result[attributes] = jsonObject[attributes];
346
+ }
347
+ }
348
+ else if (typeof attributes === 'object' && attributes !== null) {
349
+ for (const [newKey, originalKey] of Object.entries(attributes)) {
350
+ if (originalKey in jsonObject) {
351
+ result[newKey] = jsonObject[originalKey];
352
+ }
353
+ }
354
+ }
355
+
356
+ return result;
357
+ } catch (error) {
358
+ console.error('Error in getPartial:', error);
359
+ return {};
360
+ }
361
+ }
362
+
363
+ function getPartialDeep(jsonObject, attributePaths) {
364
+ try {
365
+ if (typeof jsonObject === 'string') {
366
+ jsonObject = JSON.parse(jsonObject);
367
+ }
368
+
369
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
370
+ return {};
371
+ }
372
+
373
+ const result = {};
374
+
375
+ function getValueFromPath(obj, path) {
376
+ const parts = path.split('.');
377
+ let current = obj;
378
+
379
+ for (const part of parts) {
380
+ if (current && typeof current === 'object' && part in current) {
381
+ current = current[part];
382
+ } else {
383
+ return undefined;
384
+ }
385
+ }
386
+
387
+ return current;
388
+ }
389
+
390
+ if (Array.isArray(attributePaths)) {
391
+ for (const path of attributePaths) {
392
+ const value = getValueFromPath(jsonObject, path);
393
+ if (value !== undefined) {
394
+ const key = path.split('.').pop();
395
+ result[key] = value;
396
+ }
397
+ }
398
+ }
399
+ else if (typeof attributePaths === 'object' && attributePaths !== null) {
400
+ for (const [newKey, path] of Object.entries(attributePaths)) {
401
+ const value = getValueFromPath(jsonObject, path);
402
+ if (value !== undefined) {
403
+ result[newKey] = value;
404
+ }
405
+ }
406
+ }
407
+
408
+ return result;
409
+ } catch (error) {
410
+ console.error('Error in getPartialDeep:', error);
411
+ return {};
412
+ }
413
+ }
414
+
415
+ function getPartialWithDefaults(jsonObject, attributesConfig) {
416
+ try {
417
+ if (typeof jsonObject === 'string') {
418
+ jsonObject = JSON.parse(jsonObject);
419
+ }
420
+
421
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
422
+ return {};
423
+ }
424
+
425
+ const result = {};
426
+
427
+ function getValueFromPath(obj, path, defaultValue) {
428
+ const parts = path.split('.');
429
+ let current = obj;
430
+
431
+ for (const part of parts) {
432
+ if (current && typeof current === 'object' && part in current) {
433
+ current = current[part];
434
+ } else {
435
+ return defaultValue;
436
+ }
437
+ }
438
+
439
+ return current;
440
+ }
441
+
442
+ for (const [outputKey, config] of Object.entries(attributesConfig)) {
443
+ if (typeof config === 'string') {
444
+ result[outputKey] = getValueFromPath(jsonObject, config, undefined);
445
+ } else if (typeof config === 'object' && config !== null) {
446
+ const path = config.path || outputKey;
447
+ const defaultValue = config.default;
448
+ let value = getValueFromPath(jsonObject, path, defaultValue);
449
+
450
+ if (config.transform && typeof config.transform === 'function') {
451
+ value = config.transform(value);
452
+ }
453
+
454
+ result[outputKey] = value;
455
+ }
456
+ }
457
+
458
+ return result;
459
+ } catch (error) {
460
+ console.error('Error in getPartialWithDefaults:', error);
461
+ return {};
462
+ }
463
+ }
464
+
465
+ function excludeAttributes(jsonObject, attributesToExclude) {
466
+ try {
467
+ if (typeof jsonObject === 'string') {
468
+ jsonObject = JSON.parse(jsonObject);
469
+ }
470
+
471
+ if (typeof jsonObject !== 'object' || jsonObject === null) {
472
+ return {};
473
+ }
474
+
475
+ const result = { ...jsonObject };
476
+
477
+ if (Array.isArray(attributesToExclude)) {
478
+ for (const attr of attributesToExclude) {
479
+ delete result[attr];
480
+ }
481
+ }
482
+ else if (typeof attributesToExclude === 'string') {
483
+ delete result[attributesToExclude];
484
+ }
485
+
486
+ return result;
487
+ } catch (error) {
488
+ console.error('Error in excludeAttributes:', error);
489
+ return {};
490
+ }
491
+ }
492
+
493
+ function getSize(jsonObject) {
494
+ try {
495
+ const jsonString = typeof jsonObject === 'string'
496
+ ? jsonObject
497
+ : JSON.stringify(jsonObject);
498
+ return new Blob([jsonString]).size;
499
+ } catch (error) {
500
+ console.error('Error in getSize:', error);
501
+ return 0;
502
+ }
503
+ }
504
+
505
+ function sortBy(array, key, ascending = true) {
506
+ try {
507
+ if (!Array.isArray(array)) return array;
508
+
509
+ return [...array].sort((a, b) => {
510
+ const aValue = typeof key === 'function' ? key(a) : a[key];
511
+ const bValue = typeof key === 'function' ? key(b) : b[key];
512
+
513
+ if (aValue < bValue) return ascending ? -1 : 1;
514
+ if (aValue > bValue) return ascending ? 1 : -1;
515
+ return 0;
516
+ });
517
+ } catch (error) {
518
+ console.error('Error in sortBy:', error);
519
+ return array;
520
+ }
521
+ }
522
+
135
523
  module.exports = {
136
524
  getString,
137
525
  getFile,
@@ -146,4 +534,14 @@ module.exports = {
146
534
  getJSON,
147
535
  beautifyJSON,
148
536
  beautify,
149
- };
537
+ getAttributes,
538
+ getMeta,
539
+ getMetaDetail,
540
+ getMetaCompact,
541
+ getPartial,
542
+ getPartialDeep,
543
+ getPartialWithDefaults,
544
+ excludeAttributes,
545
+ getSize,
546
+ sortBy
547
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@terzogenito/json-utils",
3
- "version": "1.0.9",
4
- "description": "Check JSON Format",
3
+ "version": "1.0.11",
4
+ "description": "JSON data utilities",
5
5
  "main": "index.js",
6
6
  "files": [
7
7
  "index.js"
@@ -19,10 +19,17 @@
19
19
  "keywords": [
20
20
  "nodejs",
21
21
  "module",
22
+ "utils",
23
+ "tools",
22
24
  "json",
23
25
  "check",
24
- "utils"
26
+ "beautify",
27
+ "analysis"
25
28
  ],
26
29
  "author": "Terzogenito",
27
- "license": "MIT"
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/terzogenito/json-utils.git"
34
+ }
28
35
  }