Minh Dao
Minh Dao

Reputation: 837

Jolt transform array of objects to key-value

Problems

Hi, I'm using Jolt to transform e-commerce products data. For e.g:

[
  {
    "objectID": 1,
    "string_facet": [
      {
        "facet_name": "eco_collection",
        "facet_value": "No"
      },
      {
        "facet_name": "performance_fabric",
        "facet_value": "No"
      }
    ]
  },
  {
    "objectID": 2,
    "string_facet": [
      {
        "facet_name": "activity",
        "facet_value": [
          "Hiking"
        ]
      }
    ]
  }
]

And my desired output is:

[
    {
        "objectID": 1,
        "string_facet": {
            "eco_collection": "No",
            "performance_fabric": "No"
        }
    },
    {
        "objectID": 2,
        "string_facet": {
            "activity": [
                "Hiking"
            ]
        }
    }
]

What I have done so far

I have tried this spec, but it isn't what I need:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&1].&",
        "string_facet": {
          "*": {
            "@facet_value": "[&1].string_facet.@facet_name"
          }
        }
      }
    }
  }
]

I'm looking for an explanation in addition to solution.

Any help would be much appreciated!

Upvotes: 1

Views: 1364

Answers (1)

Barbaros Özhan
Barbaros Özhan

Reputation: 65408

You principally need "@facet_value": "@facet_name" match, start with it, then add

  • &2 to represent going two levels up and grabbing the key name's value(string_facet)

  • &3 to represent going three levels up and grabbing the indices of the main array to accumulate each attributes nested within individual object of their own.

Then, add an extra shift transformation spec to get rid of the integer key names such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "&1.&",
        "string_facet": {
          "*": {
            "@facet_value": "&3.&2.@facet_name"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]

the demo on the site http://jolt-demo.appspot.com/ is

enter image description here

Upvotes: 1

Related Questions