将Json嵌套映射转换为键值对

时间:2019-06-12 02:59:29

标签: groovy

我有一个脚本,该脚本从URL提取JSON数据并将其解析为映射

我想将嵌套Map转换为Single Key-Value对。 例如:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
                "title": "S",
        }
    }
}

收件人

{
    "glossary_title":  "example glossary",
    "glossary_GlossDiv_title": "S"
}

这是我当前必须获取JSON数据的代码。

import groovy.json.JsonSlurper

String urlString = "https://pastebin.com/raw/SkACvctU"

def parsedJson = new JsonSlurper().parse(urlString.toURL())

println parsedJson

3 个答案:

答案 0 :(得分:1)

这是要转换的代码:

def json = '{' +
            '    "glossary": {' +
            '        "title": "example glossary",' +
            '        "GlossDiv": {' +
            '                "title": "S",' +
            '        }' +
            '    }' +
            '}'


    def jsonSlurper = new JsonSlurper()
    def parsed = jsonSlurper.parseText(json)

    def title = parsed.glossary.title
    def divTitle = parsed.glossary.GlossDiv.title

    def map = ["glossary_title":title, "glossary_GlossDiv_title":divTitle]
    println JsonOutput.toJson(map)

答案 1 :(得分:1)

您可以使用多态来获得其他递归解决方案:

import groovy.json.JsonSlurper

String urlString = "https://pastebin.com/raw/DAGee5Ad"

def parsedJson = new JsonSlurper().parse(urlString.toURL())

def flatten(Map value, List<String> prefix = []) {

   value.collectEntries { k, v ->
      flatten(v, prefix + k)
   }
}

def flatten(List value, List<String> prefix = []) {
   value.indexed().collectEntries { i, v ->
       flatten(v, prefix + i)
   }
}

def flatten(Object value, List<String> prefix = []) {
   [(prefix.join('_')): value]
}

flatten(parsedJson).each { println it }

哪个打印得更完整:

glossary_title=example glossary
glossary_GlossDiv_title=S
glossary_GlossDiv_GlossList_GlossEntry_ID=SGML
glossary_GlossDiv_GlossList_GlossEntry_SortAs=SGML
glossary_GlossDiv_GlossList_GlossEntry_GlossTerm=Standard Generalized Markup Language
glossary_GlossDiv_GlossList_GlossEntry_Acronym=SGML
glossary_GlossDiv_GlossList_GlossEntry_Abbrev=ISO 8879:1986
glossary_GlossDiv_GlossList_GlossEntry_GlossDef_para=A meta-markup language, used to create markup languages such as DocBook.
glossary_GlossDiv_GlossList_GlossEntry_GlossDef_GlossSeeAlso_0_host1=GML
glossary_GlossDiv_GlossList_GlossEntry_GlossDef_GlossSeeAlso_0_host2=XML
glossary_GlossDiv_GlossList_GlossEntry_GlossSee=markup

答案 2 :(得分:0)

我写了一个递归函数来遍历JSON并创建一个奇异映射。 下面是将嵌套Map转换为奇异Map的完整功能。

componentDidMount() {
   const { id } = this.props.match.params
   if(id) {
      this.fetchOffer(id);
   }

}


fetchOffer(id) {

  fetch(`/api/offers/${id}`)
   ....
}

输出:

import groovy.json.JsonSlurper
String urlString = "https://pastebin.com/raw/DAGee5Ad"
def parsedJson = new JsonSlurper().parse(urlString.toURL())

Map<String, String> result = new LinkedHashMap();
public void toMap(Object json, String key, Map result){

    json = [(key): json]

    json.each {k, v ->
      if( v instanceof Map ){
        v.each { k1, v1 -> 
            if (v1 instanceof Map)
                toMap(v1, k + "_" + k1 , result)
            else if(v1 instanceof List){
                def count = 1
                v1.each{ v2 ->
                    toMap(v2, k + k1 + count.toString(), result)
                    count = count + 1
                }
            }
            else
                result.put(k + "_" + k1, v1)
        }
      }
    }
}

//Calling the function 
toMap(parsedJson, "json", result)

//Printing the result
result.each{ k, v ->
    println "${k}: ${v}"
}