1

I have a json like this:

{
    "name": "Team Wolf",
    "www": "http://www.teamwolf.qqq",
    "department": "department1",
    "team1": "team1"
  },
  {
    "name": "Team Fox",
    "www": "http://www.teamfox.qqq",
    "department": "department1",
    "team2": "team2"
  },
 {
    "name": "Team Falcon",
    "www": "http://www.teamfalcon.qqq",
    "department": "department1",
    "team3": "team3"
  }

And I need to transform it in a json structured like this:

'department1': {
            'team1': {
              'name':'Team Wolf',
              'www': 'http://www.teamwolf.qqq'
            },
            'team2': {
              'name':'Team Fox',
              'www': 'http://www.teamfox.qqq'
            },
            'team3': {
              'label':'Team Falcon',
              'www': 'http://www.teamfalcon.qqq'
            }

In simple terms, I need to group the data by 'department1'. Any suggestions would be much appreciated.

user5542056
  • 55
  • 2
  • 7
  • Try mapping json to Java object with tools like gson or Jackson. The see http://stackoverflow.com/questions/21678430/group-a-list-of-objects-by-an-attribute-java to know how to group objects by attribute in java. – Giuseppe Marra Feb 16 '16 at 17:01

1 Answers1

0

https://github.com/octomix/josson

    Josson josson = Josson.fromJsonString(
        "[{" +
        "    \"name\": \"Team Wolf\"," +
        "    \"www\": \"http://www.teamwolf.qqq\"," +
        "    \"department\": \"department1\"," +
        "    \"team1\": \"team1\"" +
        "  }," +
        "  {" +
        "    \"name\": \"Team Fox\"," +
        "    \"www\": \"http://www.teamfox.qqq\"," +
        "    \"department\": \"department1\"," +
        "    \"team2\": \"team2\"" +
        "  }," +
        " {" +
        "    \"name\": \"Team Falcon\"," +
        "    \"www\": \"http://www.teamfalcon.qqq\"," +
        "    \"department\": \"department1\"," +
        "    \"team3\": \"team3\"" +
        "  }]");
    JsonNode node = josson.getNode(
        "group(department).map(" +
        "    department:: elements.map(" +
        "        ~'^team.*':: map(" +
        "            name, www" +
        "        )" +
        "    )" +
        "    .mergeObjects()" +
        ")");
    System.out.println(node.toPrettyString());

Output

[ {
  "department1" : {
    "team1" : {
      "name" : "Team Wolf",
      "www" : "http://www.teamwolf.qqq"
    },
    "team2" : {
      "name" : "Team Fox",
      "www" : "http://www.teamfox.qqq"
    },
    "team3" : {
      "name" : "Team Falcon",
      "www" : "http://www.teamfalcon.qqq"
    }
  }
} ]
Raymond Choi
  • 1,065
  • 2
  • 7
  • 8