readJSON
: Read JSON from files in the workspace.
Reads a file in the current working directory or a String as a plain text JSON file. The returned object is a normal Map with String keys or a List of primitives or Map.
Example:
def props = readJSON file: 'dir/input.json'
assert props['attr1'] == 'One'
assert props.attr1 == 'One'
def props = readJSON text: '{ "key": "value" }'
assert props['key'] == 'value'
assert props.key == 'value'
def props = readJSON text: '[ "a", "b"]'
assert props[0] == 'a'
assert props[1] == 'b'
def props = readJSON text: '{ "key": null, "a": "b" }', returnPojo: true
assert props['key'] == null
props.each { key, value ->
echo "Walked through key $key and value $value"
}
file
(optional)Path to a file in the workspace from which to read the JSON data. Data could be access as an array or a map.
You can only specify
file
ortext
, not both in the same invocation.- Type:
String
- Type:
returnPojo
(optional)Transforms the output into a POJO type (
LinkedHashMap
orArrayList
) before returning it.By default deactivated (
false
), and a JSON object (JSONObject
orJSONArray
from json-lib) is returned.- Type:
boolean
- Type:
text
(optional)A string containing the JSON formatted data. Data could be access as an array or a map.
You can only specify
file
ortext
, not both in the same invocation.- Type:
String
- Type:
def sonarHttpRequest(method,apiUrl){
sonarApi = "http://139.198.166.235:9000/api"
response = sh returnStdout: true, script:
"""
curl --location \
--request ${method} \
${sonarApi}/${apiUrl} \
--header 'Authorization: Basic YWRtaW46YWRtaW4xMjM='
"""
response = response - "\n"
try{
result = readJSON text: "${response}"
}catch(e){
result = ""
}
return result
}
扩展流水线解析JSON数据
安装插件: Pipeline Utility Steps
现在不想在触发器里面去写这些一个一个的变量了,但是还是想获取变量的值,那么需要插件。
我们会使用到这个插件的resdJSON方法,是用来专门用来处理json数据的。如果不知道怎么使用这个插件可以在片段生成器里面查看,有处理文本和处理json数据,最后赋值给变量。
def webHookData = readJSON text: "${allData}"
String name1 = webHookData["name"]
String name2 = webHookData.name
String groupName1 = webHookData["group"]["name"]
String groupName2 = webHookData.group.name
pipeline {
agent any
stages {
stage('webHook') {
steps {
println("所有body数据 --> ${allData}")
println(name1)
println(name2)
println(groupName1)
println(groupName2)
}
}
}
}
[Pipeline] readJSON
[Pipeline] node
Running on build-01 in /data/cicd/jenkinsagent/workspace/Gitlab-Generic-Webhook-Trigger
[Pipeline] {
[Pipeline] stage
[Pipeline] { (webHook)
[Pipeline] echo
所有body数据 --> {
"name": "zhangsan",
"group": {
"name" : "jenkins"
}
}
[Pipeline] echo
zhangsan
[Pipeline] echo
zhangsan
[Pipeline] echo
jenkins
[Pipeline] echo
jenkins
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
所以有两种方法,一种是在webhook里面将每个参数都写出来,另外一种是使用readJSON去处理。