JSON ist ein Format, das lesbaren Text verwendet, um Datenobjekte zu übertragen, die aus Attribut-Wert-Paaren und Array-Datentypen bestehen. Also, im Allgemeinen ist JSON ein formatierter Text.
In groovy JSON-Objekt ist nur eine Sequenz von Karten/Arrays.
Parsen json JsonSlurperClassic mit
//use JsonSlurperClassic because it produces HashMap that could be serialized by pipeline
import groovy.json.JsonSlurperClassic
node{
def json = readFile(file:'message2.json')
def data = new JsonSlurperClassic().parseText(json)
echo "color: ${data.attachments[0].color}"
}
json Pipeline
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
Gebäude json von Code Parsen und schreiben Sie es
import groovy.json.JsonOutput
node{
//to create json declare a sequence of maps/arrays in groovy
//here is the data according to your sample
def data = [
attachments:[
[
fallback: "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
pretext : "New open task [Urgent]: <http://url_to_task|Test out Slack message attachments>",
color : "#D00000",
fields :[
[
title: "Notes",
value: "This is much easier than I thought it would be.",
short: false
]
]
]
]
]
//two alternatives to write
//native pipeline step:
writeJSON(file: 'message1.json', json: data)
//but if writeJSON not supported by your version:
//convert maps/arrays to json formatted string
def json = JsonOutput.toJson(data)
//if you need pretty print (multiline) json
json = JsonOutput.prettyPrint(json)
//put string into the file:
writeFile(file:'message2.json', text: json)
}
Datei
in Titel der Frage, die Sie über das Parsen fragen, und in Frage stellen Sie sich Fragen über das Erstellen von JSON-Datei. Könnten Sie bitte klarstellen, was Sie wollen/versuchen zu tun? – daggett
@daggett Ich möchte dieses JSON-Objekt in eine groovige Variable erstellen. –