JSON एक ऐसा प्रारूप है जो मानव-पठनीय पाठ का उपयोग डेटा ऑब्जेक्ट्स को संचारित करने के लिए करता है जिसमें विशेषता-मूल्य जोड़े और सरणी डेटा प्रकार होते हैं। तो, सामान्य जेसन में एक स्वरूपित पाठ है।
ग्रोवी जेसन ऑब्जेक्ट में मानचित्र/सरणी का अनुक्रम है।
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}"
}
का उपयोग कर json पार्स करने json कोड से
node{
def data = readJSON file:'message2.json'
echo "color: ${data.attachments[0].color}"
}
इमारत json पाइपलाइन का उपयोग कर पार्स करने और फाइल करने के लिए इसे लिखने
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)
}
प्रश्न के शीर्षक में आप पार्सिंग के बारे में पूछते हैं, और सवाल में आप जेसन फ़ाइल बनाने के बारे में पूछते हैं। क्या आप कृपया स्पष्ट कर सकते हैं कि आप क्या चाहते हैं/करने का प्रयास करें। – daggett
@daggett मैं उन JSON ऑब्जेक्ट को एक groovy चर में बनाना चाहता हूं। –