Giter Club home page Giter Club logo

json-mapping's Introduction

JSON Mapping

npm Build Status Dependency Status XO code style

Transform a JSON object structure.

Install

npm install json-mapping

Usage

const mapping = require('json-mapping');

let json = {
	"appURL": "localhost",
	"object1": {
		"bool": true,
		"name": "app"
	}
};

json = mapping.map(json, [
	{
	    oldKey: "appURL",
	    newKey: "url"
	},
	{
	    oldKey: "object1.bool",
	    newKey: "object1.enabled"
	}
]);
/*
{
	"url": "localhost",
	"object1": {
		"enabled": true,
		"name": "app"
	}
}
*/

Arguments

Name Type Description
json object The initial JSON object to be mapped
mapping* array An array containing the mapping options
*mapping
Name Type Description
oldKey string The old property name to be mapped
newKey string The new property name to be mapped
values** array An array of mapped values for this property mapping
dependsOn** object Determines the value for the newKey based on a condition
**values
Name Type Description
oldValue any The old value of the property to be mapped
newValue any The new value of the property to be mapped
**dependsOn
Name Type Description
key string The key to look for
if any The value to evaluate for the key
ifValue any When key === if, this will be the value of the newKey
elseValue any When key !== if, this will be the value of the newKey

Methods

Name Type Return Description
map function object Maps a JSON object using mapping options

Changelog

See changelog.

License

MIT © Vincent Morneau

json-mapping's People

Contributors

loebelch avatar vincentmorneau avatar

Stargazers

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

Watchers

 avatar

json-mapping's Issues

It's not possible to use "values" for more than one element in array

json-mapping version 1.1.4 (latest)

My mappingtable contains two elements in "values"-array:

[
  {
    "oldKey": "mykey",
    "newKey": "myNewKey",
    "values": [
      {
        "oldValue": 1,
        "newValue": "Number 1"
      },
      {
        "oldValue": 2,
        "newValue": "Number 2"
      }
    ]
  }
]

But the values were only replaced, if there is a match in the 2nd element.

Example:

  • Result for a JSON { "mykey": 1} will be empty => {}
  • But a JSON { "mykey": 2} will be mapped/replaced correctly to { myNewKey: 'Number 2' }

So how is it possible to replace more than one value?

Complete code:

const mapping = require('json-mapping');

let json1 = {
       "mykey": 1
};

let json2 = {
       "mykey": 2
}

let mappingtable = [
    {
        oldKey: "mykey",
        newKey: "myNewKey",
        values: [ {"oldValue": 1, "newValue": "Number 1" },{ "oldValue": 2, "newValue": "Number 2" }]
    }
];

let result1 = mapping.map(json1, mappingtable);
let result2 = mapping.map(json2, mappingtable);

console.log("result 1:");
console.log(result1);
console.log("result 2:");
console.log(result2);

Result:

node test.js

result 1:
{}
result 2:
{ myNewKey: 'Number 2' }

Structure flattening/consolidation

Was wondering if you knew of a way to express flattening and consolidating a JSON data structure with how your script is currently implemented. Instead of mapping actual data, the goal is to essentially map schema. For example, I have a current schema which includes keys to express the types of nested data.

original schema
{
  history: {
    approved: {
      modification: [
        {
          dateTime: "",
          userDisplayName: "",
          userDn: ""
        }
      ]
    },
    broughtUnderEdit: {
      modification: [
        {
          dateTime: "",
          userDisplayName: "",
          userDn: ""
        }
      ]
    },
    changed: {
      modification: [
        {
          dateTime: "",
          userDisplayName: "",
          userDn: ""
        }
      ]
    },
    created: {
      dateTime: "",
      userDisplayName: "",
      userDn: ""
    },
    projectId: "",
    projectName: "",
    projectType: ""
  }
}

The goal is to reduce the levels of data hierarchy and create a result like this:

{
  "history": [
    { 
      "projectId": "",
      "projectName": "",
      "projectType": "",
      "dateTime":"",
      "type": ["approved", "broughtUnderEdit", "changed", "created"],
      "userDisplayName": "",
      "userDn": ""
    }
  ]
}

The closest thing I can create relies heavily on rewriting the value and doesn't explicitly define the mapping of all the keys other than approved. Here's the example:

const flattened = mapping.map(orig, [
  {
    oldKey: "history.approved.modification[0]",
    newKey: "history",
    values: [
      {
        oldValue: orig.history.approved.modification[0],
        newValue: [
          _.merge(orig.history.approved.modification[0], {
            type: ["approved", "changed", "broughtUnderEdit", "created"],
            projectId: orig.history.projectId,
            projectName: orig.history.projectName,
            projectType: orig.history.projectType
          })
        ]
      }
    ]
  }
]);

I'm thinking the answer is no but was curious if you knew a way to make it work without modifying the code. Thanks for any input!

There's also a sandbox here: https://codesandbox.io/embed/k9rmnlwmm7

Should allow oldKey === newKey

Right now, we have to make it a 2 step process:

json = mapping.map(json, [
		{
			oldKey: 'object1.bool',
			newKey: 'object1.boo'
		},
		
		{
			oldKey: 'object1.boo',
			newKey: 'object1.bool',
			values: [{
				oldValue: true,
				newValue: false
			}]
	    }]);

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.