2

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']])}

1 Answer 1

3

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

1 Comment

Brilliant. Thank you. I added your pretty json to my question, would you mind removing it from your answer? It's just so the answer looks better in howdoi and helpmecode etc. Cheers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.