JSON là định dạng sử dụng văn bản có thể đọc được của con người để truyền các đối tượng dữ liệu bao gồm cặp thuộc tính – giá trị và loại dữ liệu mảng. Vì vậy, nói chung json là một văn bản được định dạng.
Trong đối tượng json groovy chỉ là một chuỗi các bản đồ/mảng.
phân tích cú pháp JSON sử dụng JsonSlurperClassic
//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}"
}
phân tích cú pháp JSON sử dụng đường ống dẫn
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
xây dựng json từ mã và ghi nó vào tập tin
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)
}
trong tiêu đề câu hỏi bạn hỏi về phân tích cú pháp và bản thân bạn đang thắc mắc về việc tạo tệp json. bạn có thể vui lòng làm rõ những gì bạn muốn/cố gắng làm. – daggett
@daggett tôi muốn tạo các đối tượng JSON đó thành biến groovy. –