use jsonSlurper.parseText for text that has dash - groovy

How can I use jsonSlurper.parseText to parse "807-000" that has dash in it with groovy ?

You are generating the below string for parsing:
[807-000]
What I think you wanted is an json array containing a string:
["807-000"]
You could generate that json yourself:
def arr2 = "[" + arr.collect({ '"' + it + '"' }).join(",") + "]"
But why reinvent the wheel, when you can do it like this:
def arr2 = groovy.json.JsonOutput.toJson(arr)

It's not entirely clear what exactly do you want to do. parseText() is waiting for json to be input. I suggest several options for parsing.
def text = jsonSlurper.parseText("""{ "key": "807-000" } """)
Or did you mean that before the dash is the key, and after it is the value? If so then you can try this:
def map = "807-000".split("-").toSpreadMap()
map.each {row ->
def parsedText = jsonSlurper.parseText("""{ "${row.key}": "${row.value}" } """)
println(parsedText)
}
output is = [807:000]

How can I use jsonSlurper.parseText to parse "807-000" that has dash
in it with groovy ?
I am not sure what the challenge actually is. Something I can think of is possibly you are having trouble using Groovy property access to retrieve the value of a key when the key has a hyphen in it. You can do that by quoting the property name:
String jsonString = '''
{"807-000":"Eight O Seven"}
'''
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)
// quote the property name which
// contains a hyphen...
String description = json.'807-000'
assert description == 'Eight O Seven'

Related

Groovy script to split a file line at ',' and create a new XML file

I am very new to Groovy and trying to figure my way out.
I am trying to write a groovy to split the lines of a file on encountering ',' and then write a if condition based on the first two characters of the line. After that I wanted to create a XML file using the different data in the file. This is how far I have reached.
def Message processData(Message message) {
//Body
def body = message.getBody(java.lang.String)as String;
def varStringWriter = new StringWriter();
def varXMLBuilder = new MarkupBuilder(varStringWriter);
String newItem ;
body.eachLine{
line -> newItem = line ;
String newItem1 = newItem.substring(0,2).trim();
String newItem2 = newItem.substring(3,11).trim();
varXMLBuilder.RECORD{
node1(newItem1);
node2(newItem2);
}
}
def xml = varStringWriter.toString();
xml="<RECORDS>"+xml+"</RECORDS>" ;
message.setBody(xml);
return message;
}
In the above code I tried to use offset but, since each of my file lines are of different length it wont work.
Please help me handle this issue.
Regards,
Nisha
Splitting on a character can be done like this:
data = 'axaratgxrgc,rxregxsergcs'
def lines = data.split(/,/)
assert lines[0] == 'axaratgxrgc'
assert lines[1] == 'rxregxsergcs'
Welcome, first of all, to groovy and Stack Overflow :)
You can use tokenize() to split a string, as shown bellow.
And yeah, don't worry about ; in groovy ;)
def Message processData(Message message) {
//Body
def body = message.getBody(java.lang.String) as String;
def varStringWriter = new StringWriter()
def varXMLBuilder = new MarkupBuilder(varStringWriter)
body.eachLine { line ->
def newItems = line.tokenize(',') // input is a list of chars that will split your string, usually better than .split()
String newItem1 = newItems.first() // looks like you want just two items
String newItem2 = newItems.last() // but you can use as an array as well newItems[0] and newItems[1]
varXMLBuilder.RECORD {
node1(newItem1)
node2(newItem2)
}
}
def xml = varStringWriter.toString()
xml="<RECORDS>${xml}</RECORDS>" // you can use ${} to add a variable inside a string
message.setBody(xml)
return message
}

Need to remove unwanted symbols from value using replaceAll method

I am getting the value of a field as ["value"]
I want to print only the value removing the [ "from the result value.
That looks like a JSON array of Strings? No idea, as you don't provide any context, but you could do:
import groovy.json.JsonSlurper
def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()
println result
Prints value
The following script should be what you need
def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))

how to pass complex string to pymongo for query by python?

I need to filter the webserver requests and setting a query for pymongo, its not so simple as I need to have "and", or "or" functionality for multiple fields.
I have filtered the get request, got the parameters, built the string to be passed to db..find. But it throws error. I have identified the error as because I am forming a string like this to passed to the function, now as its a string and not actually a dict, its throwing an error. What is the right way of doing it?
Actually, I have to get something like: {$and:[{Title:{"$regex":"Hong Kong"}},{Url:{"$regex":"hong"}}]}{'_id':0, 'Body':0}
The get request I am sending is: http://127.0.0.1:5000/getRequest?Title="Hong Kong protest"&Url="hong" Now the below thing gives the exact required string, but it throws an error as its not supposed to be string. Please help.
#app.route('/getRequest', methods=['GET'])
def request():
global connection
args = request.args
if len(args) > 1:
search_str = ""
for key, val in args.items():
search_str += '{'+key+':{"$regex":'+str(val)+'}},'
search_str = search_str[:-1]
display_dict={'id':0, 'Body':0}
final_search_str = "{$and:["+search_str+"]},{'_id':0, 'Body':0}"
#return(final_search_str)
# query_str = request.args.get('query_string')
db = connection['test']
collection = db['collect1']
output = []
for s in collection.find(final_search_str):
output.append({'Title' : s['Title'], 'Url' : s['Url']})
It should be dict which should be passed to the function. Any better way to do this complex query via pymongo?
You can do this using re and bson.regex.Regex module.
http://api.mongodb.com/python/current/api/bson/regex.html
import re
from bson.regex import Regex
query = {}
for key, val in args.items():
pattern = re.compile(val)
regex = Regex.from_native(regex)
query[key] = regex
for s in collection.find(query):
output.append({'Title' : s['Title'], 'Url' : s['Url']})

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.
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
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

Is there a way to declare a Groovy string format in a variable?

I currently have a fixed format for an asset management code, which uses the Groovy string format using the dollar sign:
def code = "ITN${departmentNumber}${randomString}"
Which will generate a code that looks like:
ITN120AHKXNMUHKL
However, I have a new requirement that the code format must be customizable. I'd like to expose this functionality by allowing the user to set a custom format string such as:
OCP${departmentNumber}XI${randomString}
PAN-${randomString}
Which will output:
OCP125XIBQHNKLAPICH
PAN-XJKLBPPJKLXHNJ
Which Groovy will then interpret and replace with the appropriate variable value. Is this possible, or do I have to manually parse the placeholders and manually do the string.replace?
I believe that GString lazy evaluation fits the bill:
deptNum = "C001"
randomStr = "wot"
def code = "ITN${deptNum}${->randomStr}"
assert code == "ITNC001wot"
randomStr = "qwop"
assert code == "ITNC001qwop"
I think the original poster wants to use a variable as the format string. The answer to this is that string interpolation only works if the format is a string literal. It seems it has to be translated to more low level String.format code at compile time. I ended up using sprintf
baseUrl is a String containing http://example.com/foo/%s/%s loaded from property file
def operation = "tickle"
def target = "dog"
def url = sprintf(baseUrl, operation, target)
url
===> http://example.com/foo/tickle/dog
I believe in this case you do not need to use lazy evaluation of GString, the normal String.format() of java would do the trick:
def format = 'ITN%sX%s'
def code = { def departmentNumber, def randomString -> String.format(format, departmentNumber, randomString) }
assert code('120AHK', 'NMUHKL') == 'ITN120AHKXNMUHKL'
format = 'OCP%sXI%s'
assert code('120AHK', 'NMUHKL') == 'OCP120AHKXINMUHKL'
Hope this helps.
for Triple double quoted string
def password = "30+"
def authRequestBody = """
<dto:authTokenRequestDto xmlns:dto="dto.client.auth.soft.com">
<login>support#soft.com</login>
<password>${password}</password>
</dto:authTokenRequestDto>
"""

Resources