I am not sure how to properly parse through nested JSON using Groovy. I have included a working Python script so you can see exactly what I'm trying to do in Groovy.
JSON I need to parse:
json_payload = {"number": 3585, "url": "https://jenkins.test.com/job/test/3585/",
"displayName": "test_3585", "timestamp": 1516992464686,
"actions": [{"causes": [{"userId": "test"}]}]}
What I want to do (Python):
class JenkinsParser:
def __init__(self, json_data):
self.display_name = json_data['displayName']
self.url = json_data['url']
self.start_time = json_data['timestamp']
self.exec_url = json_data['url']
self.exec_number = json_data['number']
self.user = None
actions = json_data['actions']
for a in actions:
if 'causes' in a:
for cause in a['causes']:
if 'userId' in cause:
self.user = cause['userId']
url_split = self.execution_url.split("/job/")
self.jenkins_url = url_split[0]
self.job_name = url_split[-1].split("/")[0]
Note: The Groovy does not necessarily need to be a class, and doesn't need to use JSonSlurper
If I use JsonSlurper
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json_payload)
Can I access all the values I need like so?
result.displayName
result.url
result.timestamp
result.url
result.number
result.actions.causes.userId
I'm not sure how to grab userId..
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…