2

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

Opal
  • 81,889
  • 28
  • 189
  • 210
MaSu
  • 23
  • 2
  • 4
  • given the trivial structure you could just concat the strings and plaster the wrapping two structures in between. – cfrick Mar 04 '15 at 08:44

1 Answers1

3

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]))
Opal
  • 81,889
  • 28
  • 189
  • 210