I am working on implementing a workflow using Nextflow. Nextflow uses groovy as it's base language and then each process can use any programming language independently. I am essentially a Python programmer, so the code I've written is in Python. And am having a little trouble converting the language.

data = { "a" : "A", "b" : "B", "c" : { "somename":{ "z" : "Z", "y" : "Y", "params" :{ "minimum": "3000", "ignore": "60", "maximum_A": "2500", "maximum_B": "500" } }, "somename2":{ "z" : "Z", "y" : "Y", "params" :{ "minimum": "3000", "ignore": "60", "maximum_A": "2500", "maximum_B": "500" } } } } CNS_PARAM_LIST = [] my_dict = {} for each in data["c"]: for k, v in data["c"][each].get('params', {}).items(): CNS_PARAM_LIST.extend([k, str(v)]) my_dict[each] = CNS_PARAM_LIST print(my_dict) 

Basically, I have a JSON (data) and I need to make a dictionary from some nested fields. The output for the above code is:

{'somename': ['minimum', '3000', 'ignore', '60', 'maximum_A', '2500', 'maximum_B', '500', 'minimum', '3000', 'ignore', '60', 'maximum_A', '2500', 'maximum_B', '500'], 'somename2': ['minimum', '3000', 'ignore', '60', 'maximum_A', '2500', 'maximum_B', '500', 'minimum', '3000', 'ignore', '60', 'maximum_A', '2500', 'maximum_B', '500']} 

Simply, make somename and somename2 the keys, and make params the values.

Any groovy coder that could crack this in 1/100th the time I can? I'm sure there is also some way to make this code more efficient, any ideas are welcome!

1

1 Answer

I guess you just misspelled when duplicated keys for each somename

the first diff in groovy is how to declare a map (dictionary in python)

my_dict = [:] 

more about groovy collections you can find here:

the code for your case:

def data = [ "a" : "A", "b" : "B", "c" : [ "somename":[ "z" : "Z", "y" : "Y", "params" :[ "minimum": "3000", "ignore": "60", "maximum_A": "2500", "maximum_B": "500" ] ], "somename2":[ "z" : "Z", "y" : "Y", "params" :[ "minimum": "3000", "ignore": "60", "maximum_A": "2500", "maximum_B": "500" ] ] ] ] def my_dict = data.c.collectEntries{k,v-> [k,v.params] } println my_dict //if you want to print it as json: println groovy.json.JsonOutput.toJson(my_dict) 

i'm using collectEntries method on Map object

you could find other methods for Map in GDK documentation: groovy Map just google gdk map

as soon as groovy Map extends java Map check main methods in javadoc: java Map

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.