MaSu
MaSu

Reputation: 23

Concatenation of JSON Arrays/Objects using Groovy

How can two independent different JSON Arrays or JSON Objects be merged or concatenated and treated as a single JSON Object using Java or Groovy.

See below sample JSON independent Objects i have First one holds Duties information

[
  {
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }]

Second JSON object holds Certificates infomation

 [
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }]

I need to concatenate and access both the JSONs in below format `

{
  "duties":
  [{
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }],
  "Certificates":
  [
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }
  ]
  }

Please let me know the option available to get this done. Thanks

Upvotes: 2

Views: 5800

Answers (1)

Opal
Opal

Reputation: 84784

It can be done e.g. in the following way:

import groovy.json.*

def json1 = """[
  {
    "code": "A0001",
    "description": "Do strategic planning for long range goals of the university"
  },
  {
    "code": "A0002",
    "description": "Administer budgets in excess of 1,000,000"
  }]"""

 def json2 = """[
  {
    "code": "CPA",
    "description": "Certified Public Accountant"
  },
  {
    "code": "CPR",
    "description": "Cardiopulmonary Resuscitation"
  },
  {
    "code": "ELE",
    "description": "Electrician's License"
  }]"""

  def duties = new JsonSlurper().parseText(json1)
  def certs = new JsonSlurper().parseText(json2)  

  println JsonOutput.prettyPrint(JsonOutput.toJson ([duties: duties, certificates: certs]))

Upvotes: 3

Related Questions