Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

How to properly parse JSON in Groovy

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you can access the values like you described.

You could access userId like result?.actions.first().causes.first().userId? if you're sure your data is structured exactly like that. If you may or may not have actions, or may or may not have causes, you could do something like result?.actions?.first()?.causes?.first()?.userId? to make your access null-safe, or you could use the spread (*.) operator to access userId if there may be multiple actions or causes.

Per your comment about something returning null, this works as expected:

def json_payload = """{"number": 3585, "url": "https://jenkins.test.com/job/test/3585/", "displayName": "test_3585", "timestamp": 1516992464686, "actions": [{"causes": [{"userId": "test"}]}]}"""
def slurper = new groovy.json.JsonSlurper()
def result = slurper.parseText(json_payload)
return result?.actions?.first()?.causes?.first()?.userId?

and returns "test". If you are not seeing similar results you may have a syntax error or different key in your actual data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...