Introduction

When integrating various systems you may be required to change the way data is structured in order to make it compatible. This can be as simple as moving the field price to sales_price but may become more complex when you have to split keys and values to separate fields. Within this article, you will learn how to change the structure of data using transformers.

We want to restructure the data to group keys with their category names and values with their category names separately.


Initial data:

{
    "carbohydrates": "70 percent",
    "protein": "20 percent",
    "fat": "10 percent"
}

We want to restructure the data to group keys with their category names and values with their category names separately.


Steps to replicate

1. Create a new transformer and select the following entity transformerData, transform data using mappers and conditions.

2. Add a new data transformer and select Move data between accessors.

3. Select Source accessor as Key accessor.

4. Set Keys with the following values: carbohydrates, protein, fat.

5. Select Destination accessor as Structure accessor.

6. Set the value of Key as nutrients.

7. Set the value of Value as percentage.

8. Set the value of Root as nutritional value.

9. Press "Run test". The outcome should be as follows:


{
    "nutritional_value": [
        {
            "nutrients": "carbohydrates",
            "percentage": "70 percent"
        },
        {
            "nutrients": "protein",
            "percentage": "20 percent"
        },
        {
            "nutrients": "fat",
            "percentage": "10 percent"
        }
    ]
}

Your data restructuring transformer should look similar to this example:


Changing data structure back to key-value pair

The goal is to restructure the data to its original state and group the values of the keys with their values back together. 


Steps to implement

  1. Add a new data transformer and select Move data between accessors.
  2. Select Source accessor as Structure accessor.
  3. Set the value of Key as nutrients.
  4. Set the value of Value as percentage.
  5. Set the value of Root as nutritional value.
  6. Select Destination accessor as Key accessor.
  7. Set Keys with the following values: carbohydrates, protein, fat.
  8. Press "Run test". The outcome should be as follows:
  9. To get to the original data, we need to filter out the key"nutritional value". For this, add a new data transformer and select Key filter.
  10. Select Accessor as Key accessor.
  11. Set the value of Key as nutritional value.
  12. Press "Run test". The result should look exactly as the original payload data