cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Looping through parsed JSON to get key and value

moxiego
Deputy Chef II
Deputy Chef II

I  have a GET command that returns a JSON response.The next step is Parse JSON. From there, I want to loop through the "key" and "value". The Parsed JSON turns the fields into datapills, which I can pull the value, but I can't get the "key" (label). Is this possible?

 

2 ACCEPTED SOLUTIONS

gary1
Executive Chef III
Executive Chef III

Create a Ruby action and use the following code. Create an input called "obj" and use the object data pill. It will output an array of objects with key/value keys that are easier to loop through in a traditional Workato loop.

Ruby code:

 

 

obj = input["obj"]
array = [] 

input["obj"].keys.each { | k | 
  array.push({"key": k, "value": obj[k]})
}
  
{output: array}
  

 

 

Example input object:

 

 

{"one": 1, "two": 2, "three": 3}

 

 

Output:

 

 

{
	"output": {
		"output": [
			{
				"key": "one",
				"value": 1
			},
			{
				"key": "two",
				"value": 2
			},
			{
				"key": "three",
				"value": 3
			}
		]
	}
}

 

 

 

View solution in original post

moxiego
Deputy Chef II
Deputy Chef II

Thank you! I was able to turn it into python code that worked for me.

def main(input):
data = input.get("jsondata", [])
output_list = []

for item in data:
custom_fields = item.get("custom_fields", {})
for key, value in custom_fields.items():
output_list.append({"key": key, "value": value})

return {'output_q' : output_list}

View solution in original post

6 REPLIES 6

Prachi_chakke
Deputy Chef I
Deputy Chef I

would mind to answer how can I map these key value to data model?

 

moxiego
Deputy Chef II
Deputy Chef II

Step 10: In the above code, we get the output_q as the key/value list.

Step 11: "for each item in output_q (prev step) repeat the following steps"

Then I update previously declared variables

Primary Supervisor: KeyStep11.match?(/primary_supervisor/).present?? ValueStep11 : skip