Groovy web console

subscribe to the feed Subscribe
to this
site
Json2Json Transformation (via #groovywebconsole)
tweet this snippet Tweet
this
script

Json2Json Transformation

Published 2 weeks ago by Kiran Patel with tags json2json JsonBuilder
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
//this example transform the input json to another json structure using Groovy JsonBuilder
import groovy.json.JsonBuilder

def input = """{
  "Order": {
    "OrderNum": "222223121",
    "Items": [
      {
        "Code": "12345",
        "Name": "iPhone"
      },
      {
        "Code": "32154",
        "Name": "Samsung"
      }
    ]
  }
}"""

def inputJson = new groovy.json.JsonSlurper().parseText(input)

def output = new JsonBuilder()

output {   
    orderNumber inputJson.Order.OrderNum
    def itemArray = []
    inputJson.Order.Items.each{ item -> 
        itemArray.add({  id item.Code
            name item.Name
        })
    }
    orderItems itemArray
}

println output.toString()