09-20-2023 06:30 AM
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?
Solved! Go to Solution.
09-20-2023 09:13 AM - edited 09-20-2023 09:22 AM
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
}
]
}
}
09-21-2023 06:53 AM
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}
09-20-2023 09:13 AM - edited 09-20-2023 09:22 AM
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
}
]
}
}
09-21-2023 06:53 AM
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}
09-21-2023 07:04 AM
This is such a useful and common requirement that I really hope Workato can build it into a standard function. I had to ask for help to do this with Ruby years ago. Surely many customers come across this requirement/shortfall in functionality all the time.
09-21-2023 08:00 AM
It's a tough choice between this or fixing the "triple click list" bug!