1

Input:

 {
   "Student": {
      "name" :"abc",
      "id"   : 588, 
      "class : "12"
   }
 } 

Reqired Output:

 {
   "Student": {

      "key" :"name",
      "value":"abc",

      "key" :"id",
      "value":"588",

      "key" :"class",
      "value":"12"
   }
 } 
Komal12
  • 3,340
  • 4
  • 16
  • 25
bigdata
  • 21
  • 7

3 Answers3

2

Your output json invalid. Json object can not duplicate key .

You can use the library org.json and do something like this:

    JSONObject jsonObject = new JSONObject(inputJson);
    JSONObject outputJson = new JSONObject();
    JSONArray array = new JSONArray();

    for (Object key : jsonObject.keySet()) {
       JSONObject item = new JSONObject();

       String keyStr = (String)key;
       Object keyvalue = jsonObj.get(keyStr);
       item.put(keyStr, keyvalue);
       array.put(item);

    }
    outputJson.put("Student", array);
    System.out.println(json.toString());

Output :

 {
    "Student": [

        {
            "key": "name",
            "value": "abc"
        },

        {
            "key": "id",
            "value": "588"
        },
        {
            "key": "class",
            "value": "12"
        }
    ]

 }
Praveen
  • 432
  • 1
  • 6
  • 14
ooozguuur
  • 3,396
  • 2
  • 24
  • 42
0

Similar to the other answer, the desired output JSON format is not valid.

The closest valid output would be

{
  "Student" : [ {
    "key" : "name",
    "value" : "abc"
  }, {
    "key" : "id",
    "value" : 588
  }, {
    "key" : "class",
    "value" : "12"
  } ]
}

This can be generated via Jolt with the following spec

[
  {
    "operation": "shift",
    "spec": {
      "Student": {
        "name": {
          "$": "Student[0].key",
          "@": "Student[0].value"
        },
        "id": {
          "$": "Student[1].key",
          "@": "Student[1].value"
        },
        "class": {
          "$": "Student[2].key",
          "@": "Student[2].value"
        }
      }
    }
  }
]
Milo S
  • 4,466
  • 1
  • 19
  • 22
0

This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.

The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:

{"Student" : array(.Student)}