Groovy web console

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

Json2Json Transformation

Published 3 months ago by Kiran Patel with tags json2json transformation 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",
        "Type" : "Device"
      },
      {
        "Code": 32154,
        "Name": "Samsung",
        "Type" : "Device"
      },
      {
        "Code": 32155,
        "Name": "microsim",
        "Type" : "SIM"
      }
    ]
  }
}"""

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

def output = new JsonBuilder()

output {   
    orderNumber inputJson.Order.OrderNum
    orderItems inputJson.Order.Items
                .findAll({ it.Type == 'Device' })            //filtering
                .collect{[
                         id: it.Code,
                         name: it.Name,
                         type: it.Type
                    ]}
}

println output.toPrettyString()