简体   繁体   中英

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":"bob@boston.com"
    },
    {
      "name":"alice",
      "phone":"212-123-345",
      "ext":"1",
      "email":"alice@boston.com"
    }
  ],
  "chicago": [
    {
      "name":"charlie",
      "phone":"313-232-545",
      "ext":"14",
      "email":"charlie@chicago.com"
    },
    {
      "name":"denise",
      "phone":"414-123-546",
      "ext":"9",
      "email":"denise@chicago.com"
    }
  ]
}'''

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

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":"bob@boston.com"
    },
    {
      "name":"alice",
      "phone":"212-123-345",
      "ext":"1",
      "email":"alice@boston.com"
    }
  ],
  "chicago": [
    {
      "name":"charlie",
      "phone":"313-232-545",
      "ext":"14",
      "email":"charlie@chicago.com"
    },
    {
      "name":"denise",
      "phone":"414-123-546",
      "ext":"9",
      "email":"denise@chicago.com"
    }
  ]
}'''

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM