Brian
Brian

Reputation: 773

Parse nested json objects in groovy

I have a json file containing contact info grouped by city. I want to parse the json and create a list of names and numbers but after fiddling for an hour or so, I can't get this to work in groovy.

def ​json = '''{
  "date":"2018-01-04T22:01:02.2125",
  "boston": [
    {
      "name":"bob",
      "phone":"242 123123",
      "ext":"12",
      "email":"[email protected]"
    },
    {
      "name":"alice",
      "phone":"212-123-345",
      "ext":"1",
      "email":"[email protected]"
    }
  ],
  "chicago": [
    {
      "name":"charlie",
      "phone":"313-232-545",
      "ext":"14",
      "email":"[email protected]"
    },
    {
      "name":"denise",
      "phone":"414-123-546",
      "ext":"9",
      "email":"[email protected]"
    }
  ]
}'''

I have tried a few variations on the following theme but they all failed so far.

parsedjson = slurper.parseText(json)
phonelist = []
parsedjson.each{phonelist.add([it['name'],it['phone']])}

Upvotes: 2

Views: 4629

Answers (1)

tim_yates
tim_yates

Reputation: 171154

It's tricky with the json you have, as you need to look for the values which are lists... You can do this with a findAll, so given the json:


def ​json = '''{
  "date":"2018-01-04T22:01:02.2125",
  "boston": [
    {
      "name":"bob",
      "phone":"242 123123",
      "ext":"12",
      "email":"[email protected]"
    },
    {
      "name":"alice",
      "phone":"212-123-345",
      "ext":"1",
      "email":"[email protected]"
    }
  ],
  "chicago": [
    {
      "name":"charlie",
      "phone":"313-232-545",
      "ext":"14",
      "email":"[email protected]"
    },
    {
      "name":"denise",
      "phone":"414-123-546",
      "ext":"9",
      "email":"[email protected]"
    }
  ]
}'''

You can import the JsonSlurper and parse the json as you currently do:

import groovy.json.JsonSlurper

def parsedjson = new JsonSlurper().parseText(json)

Then;

def result = ​parsedjson.findAll { it.value instanceof List } // Find all entries with a list value
          .values()                                          // Get all the lists
          .flatten()                                         // Merge them into a single list
          .collect { [it.name, it.phone] }     ​​​​​              // grab the name and phone for each

Upvotes: 3

Related Questions