Raj P
Raj P

Reputation: 11

Jolt generating null while converting map to list

I want to remove null values from the transformed JSON using Jolt spec for the example below:

JSON input

{
  "ratings": {
    "primary": 5,
    "quality": 4,
    "design": 5
  }
}

Jolt spec

[
  {
    "operation": "shift",
    "spec": {
      "ratings": {
        "primary": "primary1",
        "*": {
          // #2 means go three levels up the tree (count from 0),
          //  and ask the "ratings" node, how many of it's
          //  children have been matched.
          //
          // This allows us to put the Name and the Value into
          //  the same object in the Ratings array.
          "$": "Ratings[#2].Name",
          "@": "Ratings[#2].Value"
        }
      }
    }
  }
]

Output

{
  "primary1" : 5,
  "Ratings" : [ null, {
    "Name" : "quality",
    "Value" : 4
  }, {
    "Name" : "design",
    "Value" : 5
  } ]
}

In the output first element of the "Rating" array is null, I want to avoid it from the list.

Upvotes: 1

Views: 251

Answers (1)

Mohammadreza Khedri
Mohammadreza Khedri

Reputation: 2691

You have 3 keys in the ratings object now. So when you ask it about how many of its children have been matched. its return 3.

So you can separate primary from the ratings object. and then using another shift operation and then asking the ratings node with #2, how many of its children have been matched. its return 2.

In this case, you can prevent of null that is produced from primary.

[
  {
    "operation": "shift",
    "spec": {
      "ratings": {
        "primary": "primary1",
        "*": "&1.&"
      }
    }
    },
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "ratings": {
        "*": {
          // #2 means go three levels up the tree (count from 0),
          //  and ask the "ratings" node, how many of it's
          //  children have been matched.
          //
          // This allows us to put the Name and the Value into
          //  the same object in the Ratings array.
          "$": "Ratings[#2].Name",
          "@": "Ratings[#2].Value"
        }
      }
    }
  }
]

Note: If you changed your input like this.

{
  "ratings": {
    "quality": 4,
    "design": 5,
    "primary": 5
  }
}

Your jolt spec working correctly.

Note that you should know when you use [#2], you are using the index of object keys. like an array. So when you change the input like above, null is the last value and jolt prevents it.

Upvotes: 1

Related Questions