UNPKG

json-transforms

Version:

Provides a recursive, pattern-matching approach to transforming JSON data.

97 lines (84 loc) 2.68 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('jspath')) : typeof define === 'function' && define.amd ? define(['exports', 'jspath'], factory) : (factory((global.jsont = global.jsont || {}),global.JSPath)); }(this, (function (exports,JSPath) { 'use strict'; JSPath = 'default' in JSPath ? JSPath['default'] : JSPath; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var identity = function identity(json, runner) { if ((typeof json === 'undefined' ? 'undefined' : _typeof(json)) !== 'object') { return json; } else if (Array.isArray(json)) { return json.map(function (d) { return runner(d); }); } else { var out = {}; for (var prop in json) { var value = json[prop]; if (Array.isArray(value)) { out[prop] = value.map(function (d) { return runner(d); }); } else { out[prop] = runner(value); } } return out; } }; var transform = function transform(json, rules) { var runner = function runner(match) { for (var i = 0; i < rules.length; i++) { var rule = rules[i]; var res = rule(match, adaptedRunner); if (res !== null) { return res; } } }; var adaptedRunner = function adaptedRunner(ast) { if (Array.isArray(ast)) { return ast.map(function (r) { return runner(r); }); } else { return runner(ast); } }; return adaptedRunner(json); }; var pathRule = function pathRule(path, ifMatch) { return function (json, runner) { var match = JSPath.apply(path, json); var unwrappedMatch = match.length === 1 ? match[0] : match; var rootMatch = unwrappedMatch === json; if (match.length > 0) { // add recursion checks around the runner var guardedRunner = function guardedRunner(leaf) { if (arguments.length === 0 && rootMatch || arguments.length === 1 && json === leaf) { console.warn('Warning: un-bounded recursion detected'); return {}; } else { return leaf ? runner(leaf) : runner(unwrappedMatch); } }; return ifMatch({ context: json, match: unwrappedMatch, runner: guardedRunner }); } else { return null; } }; }; exports.identity = identity; exports.transform = transform; exports.pathRule = pathRule; Object.defineProperty(exports, '__esModule', { value: true }); })));