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

1
  • given the trivial structure you could just concat the strings and plaster the wrapping two structures in between. Commented Mar 4, 2015 at 8:44

1 Answer 1

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]))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Opal. Super. The solution looks great and works like a char,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.