2

I have a JSON input and I want to transform it into another JSON that can be easily stored in Java POJOs. An array structure is most suitable according to me as it can be structured easily.

I have an input JSON like this:

{
  "rating-1": {
    "min": 1,
    "max": 2
  },
  "rating-2": {
    "min": 3
  }
}

I want to translate this JSON to something like this which is easy to be stored when creating Java POJOs:

{
  "Ratings" : [
    {
      "rating": "rating-1",
      "min": 1,
      "max": 2
    },
    "rating-2" : {
      "rating": "rating-2",
      "min" : 3
    }
  ]
}

The closest I could come up with was with the following jolt spec(note that few elements in the input JSON inside rating-* can be empty or null:

[
  {
    "operation": "shift",
    "spec": {
      "rating-*": {
        "$": "Ratings[#0].&1.rating",
        "min": "Ratings[#0].&1.min",
        "max": "Ratings[#0].&1.max"
      }
    }
  }
]

which gives the following output JSON:

{
  "Ratings" : [ {
    "rating-1": {
      "rating": "rating-1",
      "min": 1,
      "max": 2
    },
    {
      "rating": "rating-2",
      "min": 3
    }
  } ]
}

The issue is that this creates an extra key "rating-1" / "rating-2" which is troublesome when creating the Java objects for the JSON. What JSON spec should be written to modify it to my expected output?

Mohammadreza Khedri
  • 2,523
  • 1
  • 11
  • 22

1 Answers1

2

You can use this spec:

[
  {
    "operation": "shift",
    "spec": {
      "rating-*": {
        "$": "Ratings[#2].rating",
        "min": "Ratings[#2].&",
        "max": "Ratings[#2].&"
      }
    }
  }
]

The only note that you have to notice about that is [#2]. It can help you to achieve the index of the root-level object. for example, you have 2 objects in the root level object so you have index 0 and 1 in it.

Mohammadreza Khedri
  • 2,523
  • 1
  • 11
  • 22