如何在Groovy中正确解析JSON [英] How to properly parse JSON in Groovy
问题描述
我不确定如何使用Groovy正确解析嵌套的JSON.我包含了一个有效的Python脚本,因此您可以准确地看到我在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:
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"}]}]}
我想做什么(Python):
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]
注意:Groovy不一定需要是一个类,也不需要使用JSonSlurper
Note: The Groovy does not necessarily need to be a class, and doesn't need to use JSonSlurper
如果我使用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
我不确定如何获取用户ID.
I'm not sure how to grab userId..
推荐答案
是的,您可以访问如上所述的值.
Yes, you can access the values like you described.
如果您确定数据的结构完全一样,则可以像result.actions.first().causes.first().userId
那样访问userId.如果您可能有动作或没有动作,或者可能有或没有原因,则可以执行result.actions?.first()?.causes?.first()?.userId
之类的操作以使访问为null安全,或者可以使用split(*.
)运算符访问userId(如果存在)可能是多种动作或原因.
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.
根据您对返回null的内容的评论,此操作可以按预期进行:
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.
这篇关于如何在Groovy中正确解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!