Teddy
Teddy

Reputation: 35

groovy extract value from string

I got a string from a server response:

responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"

then I do:

responseString[1..-2].tokenize(',')

got:

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

get(3) got:

""userid":"user_1""

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 ""?

Thanks.

Upvotes: 0

Views: 2481

Answers (2)

Gaurav Khurana
Gaurav Khurana

Reputation: 3891

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":"(.*?)"/)
log.info 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

Upvotes: 0

Michael Easter
Michael Easter

Reputation: 24468

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

Upvotes: 2

Related Questions