Code Monkey home page Code Monkey logo

json-map-transform's Introduction

json-map-transform

Build Status Coverage Status

A lighweight Node library that transforms a json object or an array of json objects based on tranformation template.

Installation

Using npm:

npm i --save json-map-transform

Usage

Template

Single object transformation

Array transformation


Template

Key: Each key property in the template object describes the path to the property in the output object. This is where the value in path of the input object will be mapped to.

Path: Is the path to the property in the input object that will be mapped to the template key. It can also be an array of possible paths in case the objects doesn't follow an exact pattern.

Transform: Is a callback that can be used to transform the current property. It receives two parameters: (property, originalObject).

Default: In case a path does not exists in the input object or the value returned by transform is undefined, the default value will be used.

OmitValues: Sometimes it is necessary to ignore values on the transformation (ex: undefined, empty string or other values depending on a business rule). With the omitValues, it is possible to define an array of values that should be ignored on the transformation. The output object will not have the associated key.

Template example:

const template = {
	title: {
		path: 'name',
		transform: (val) => val.toUpperCase()
	},
	label: {
		path: ['category', 'categories'],
		omitValues: ['', undefined, 'ERROR']
	},
	vendor: {
		path: 'meta.vendor',
		default: 'No vendor'
	},
	'meta.photos': {
		path: 'photos',
		transform: (val) => val.map(photo => photo.photoUrl)
	},
	'meta.id': {
		path: 'code'
	}
}

This template will work like this:

from to transform
name title toUpperCase()
[category, categories] label
meta.vendor vendor
photos meta.photos photo.photoUrl
code meta.code

Single object transformation

const transform = require('json-map-transform');

//The json objects to be transformed
const product1 = {
	name: 'Hello world',
	code: 'BOOK01',
	category: 'books',
	price: '200',
	photos: [ 
		{ title: 'photo1', photoUrl: 'http://photo1.jpg', isCover: true },
		{ title: 'photo2', photoUrl: 'http://photo2.jpg' }
	],
	meta: {
		vendor: 'Author name'
	}
};

const product2 = {
	name: 'My Digital Product',
	code: 'DIGITAL01',
	category: 'digital',
	price: '500',
	photos: [ 
		{ title: 'photo3', photoUrl: 'http://photo3.jpg', isCover: true },
		{ title: 'photo4', photoUrl: 'http://photo4.jpg' }
	],
	meta: {
		vendor: 'Global Digital'
	}
};

convertedJson = transform(product1, template);

//Output object
{
    "title": "HELLO WORLD",
    "label": "books",
    "vendor": "Author name",
    "meta": {
        "photos": [
            "http://photo1.jpg",
            "http://photo2.jpg"
        ],
        "id": "BOOK01"
    }
}

You ca also use an optional callback to be executed after the transformation

const afterTransform = (element) => Object.assign({}, element, {
	categoryCode: element.label == 'books' ? 101 : 102
});

transform(product1, template, afterTransform);

// Output json
{
    "title": "HELLO WORLD",
    "label": "books",
    "vendor": "Author name",
    "meta": {
        "photos": [
            "http://photo1.jpg",
            "http://photo2.jpg"
        ],
        "id": "BOOK01"
    },
    "categoryCode": 101
}

Array transformation

// The afterTransform callback is also optional
transform([product1, product2], template, afterTransform);


[
    {
        "title": "HELLO WORLD",
        "label": "books",
        "vendor": "Author name",
        "meta": {
            "photos": [
                "http://photo1.jpg",
                "http://photo2.jpg"
            ],
            "id": "BOOK01"
        },
        "categoryCode": 101
    },
    {
        "title": "MY DIGITAL PRODUCT",
        "label": "digital",
        "vendor": "Global Digital",
        "meta": {
            "photos": [
                "http://photo3.jpg",
                "http://photo4.jpg"
            ],
            "id": "DIGITAL01"
        },
        "categoryCode": 102
    }
]

The afterTransform callback is called after each element tranformation.

json-map-transform's People

Contributors

edudavid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

json-map-transform's Issues

Feature request: Add an option to set a default value.

When the transform function (user-defined) returns undefined, null or an empty String, the result is an empty object.

It would be great if we could have a default value option that would be set if any of these is returned.

Cannot find declaration for module

Hi, I have imported this library in my nodejs script like so

import transform from 'json-map-transform';

but I am getting the following error

Could not find a declaration file for module 'json-map-transform'. '/home/rramanth/tonline-payments-service/node_modules/json-map-transform/index.js' implicitly has an 'any' type.
Try npm install @types/json-map-transform if it exists or add a new declaration (.d.ts) file containing declare module 'json-map-transform';ts(7016)

How do I fix this ?

Returning undefined for false or 0

If you have a boolean variable with false, or an Integer with 0, it will be undefined.

value = (value && value[subPath]) ? value[subPath] : undefined;

I think the problem is here, it should be:

value = (value && value[subPath] !== undefined) ? value[subPath] : undefined;

And further here the logic needs to be changed:

const transformedValue = (transform ? transform(value, transformedObject, originalObject) : value) || defaultValue;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.