groovy extract value from string

I got a string from a server response:


then I do:



[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]

get(3) got:


what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?


2 answers

  • answered 2018-04-14 15:21 Michael Easter

    If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:

    def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
    def matcher = (s =~ /responseString:"(.*)"/)
    assert matcher.matches()
    def responseStr = matcher[0][1]
    import groovy.json.JsonSlurper
    def jsonSlurper = new JsonSlurper()
    def json = jsonSlurper.parseText(responseStr)
    assert "user_1" ==  json.userid

  • answered 2018-04-15 04:50 Gaurav khurana

    This code can help you get you to the userid.

    def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
    def match = (str=~ /"userid":"(.*?)"/) match[0][1]

    this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that

    def match = (str=~ /"age":"(.*?)"/)

    @Michael code is also correct. Its just that you have clarified that you want the user Name to be specific