将groovy字符串转换为groovy中的地图

时间:2017-06-16 11:34:58

标签: json regex dictionary grails groovy

我需要将groovy字符串转换为地图对象。字符串完全是:

""{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}""

我需要获取对应于" name"的值。我已经尝试过使用JsonBuilder,JsonSlurper和regexp方法解决这个问题。但我还没有找到解决方案。

为了简化事情,我删除了反斜杠: $(function() { var img = $('#img').css('background-image');; imgURL = img.replace('url("','').replace('")',''); img = imgURL; alert(img); $("#img").attr("src",""+img+"").removeAttr('width').removeAttr('height'); }); 。缩小的字符串是:

ui.cssClass

期待对此有任何帮助。我使用的是grails 2.5.1和groovy 2.4.10。

4 个答案:

答案 0 :(得分:2)

你有一个json字符串,可以用JsonSlurper解析。

你走了:

def string = """{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}"""
def json = new groovy.json.JsonSlurper().parseText(string)
assert json instanceof Map​​​​​

您可以在线快速尝试 Demo

答案 1 :(得分:0)

/*

i put exactly this string into the file 1.gr
"\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""

*/

def s= new File("./1.gr").text
println s 
// output> "\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""
s=Eval.me(s)
println s 
// output> "{\"1\":[],\"2\":[],\"3\":[{\"name\":\"PVR_Test_Product\",\"id\":\"100048\"}],\"4\":[],\"5\":[]}"
s=Eval.me(s)
println s 
// output> {"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}

//now it's possible to parse json
def json = new groovy.json.JsonSlurper().parseText(s)

答案 2 :(得分:0)

有人正在向您发送数据JSON的JSON。盲目删除\可能会导致严重错误。但你可以两次de-JSON。

在这种情况下一如既往:如果有人给你提供这种形状的数据,你可以和他们交谈,确保他们完全有理由做这些事情。这通常是一种错误。

def jsonOfJson = "\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(jsonOfJson)
println(json.inspect())
// -> '{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}'
def data = slurper.parseText(json)
println(data.inspect())
// -> ['1':[], '2':[], '3':[['name':'PVR_Test_Product', 'id':'100048']], '4':[], '5':[]]
assert data["3"].size()==1

答案 3 :(得分:0)

以下代码将JSON之类的字符串转换为对象或数组:

#!/usr/bin/env groovy

/**
 * Get the nearest object or array end
 */
def getNearestEnd(String json, int start, String head, String tail) {
    def end = start
    def count = 1
    while (count > 0) {
        end++
        def c = json.charAt(end)
        if (c == head) {
            count++
        } else if (c == tail) {
            count--
        }
    }
    return end;
}

/**
 * Parse the object
 */
def parseObject(String json) {
    def map = [:]
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    def key = ''
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                if (state == 'none') {
                    def keyStart = index + 1;
                    def keyEnd = keyStart;
                    while (json.charAt(keyEnd) != '"') {
                        keyEnd++
                    }
                    index = keyEnd
                    def keyValue = json[keyStart .. keyEnd - 1]
                    key = keyValue
                } else if (state == 'value') {
                    def stringStart = index + 1;
                    def stringEnd = stringStart;
                    while (json.charAt(stringEnd) != '"') {
                        stringEnd++
                    }
                    index = stringEnd
                    def stringValue = json[stringStart .. stringEnd - 1]
                    map.put(key, stringValue)
                }
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd json, index, '{', '}'
                def objectValue = json[objectStart .. objectEnd]
                map.put(key, parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                map.put(key, parseArray(arrayValue))
                index = arrayEnd
                break

            case ':':
                state = 'value'
                break

            case ',':
                state = 'none'
                key = ''
                break;

            case ["\n", "\t", "\r", " "]:
                break

            default:
                break
        }
        index++
    }

    return map
}

/**
 * Parse the array
 */
def parseArray(String json) {
    def list = []
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                def stringStart = index + 1;
                def stringEnd = stringStart;
                while (json.charAt(stringEnd) != '"') {
                    stringEnd++
                }
                def stringValue = json[stringStart .. stringEnd - 1]
                list.add(stringValue)
                index = stringEnd
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd(json, index, '{', '}')
                def objectValue = json[objectStart .. objectEnd]
                list.add(parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                list.add(parseArray(arrayValue))
                index = arrayEnd
                break

            case ["\n", "\t", "\r", " "]:
                break

            case ',':
                state = 'none'
                key = ''
                break;

            default:
                break
        }
        index++
    }

    return list
}

/**
 * Parse the JSON, object or array
 */
def parseJson(String json) {
    def start = json[0]
    if (start == '[') {
        return parseArray(json)
    } else if (start == '{') {
        return parseObject(json)
    } else {
        return null
    }
}

// Test code
println parseJson('{"abdef":["Jim","Tom","Sam",["XYZ","ABC"]],{"namek":["adbc","cdef"]}}')