简体   繁体   English

在Groovy中解析嵌套的json对象

[英]Parse nested json objects in groovy

I have a json file containing contact info grouped by city. 我有一个json文件,其中包含按城市分组的联系信息。 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. 我想解析json并创建一个名称和数字列表,但是摆弄一个小时左右后,我无法在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: 使用您拥有的json非常棘手,因为您需要查找列表中的值...您可以使用findAll来做到这一点,因此给定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: 您可以像目前一样导入JsonSlurper并解析json:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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