[英]Groovy script: How to parse/format Json in groovy in each loop
I am new on Groovy, I am trying to mock a service in soap ui. 我是Groovy的新手,我想在soap ui中模拟服务。
Requirement is to load a text file with json data, and load a node with matching data. 要求是使用json数据加载文本文件,并使用匹配数据加载节点。
whati have tried is as below, 我尝试过的如下
def inputFile = new File("D:\\Users\\json.txt")
def InputJSON = new JsonSlurper().parseText(inputFile.text)
InputJSON.each{
def ID1 = it
it.items.each {
if(it.Number == itemNumber)
{
log.info it
requestContext.Id = ID1
}
}
}
This works perfectly fine just one issue, is the format. 格式很完美,只是一个问题。 when ID1 loads into requestContext.Id, the format of json is lost from the file.
当ID1加载到requestContext.Id中时,json格式将从文件中丢失。
What I need is 我需要的是
{
"items" {
"number" : 1475175072691
}
}
what i get is 我得到的是
{
metadata = {
timestamp = 1475175072691
}
}
Why does it take away the double quotes " and colon : from my json. Please suggest. 为什么从我的json中删除双引号“和冒号: 。请提出建议。
The following code: 如下代码:
import groovy.json.*
def str = '''\
[
{
"items":{
"number":1475175072691
}
},
{
"items":{
"number":1475175072691
}
},
{
"items":{
"number":1475175072691
}
},
{
"items":{
"number":1475175072691
}
}
]'''
def json = new JsonSlurper().parseText(str)
json.each {
println JsonOutput.prettyPrint(JsonOutput.toJson(it))
}
prints out the following result: 打印出以下结果:
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
In other words, you need to serialize and pretty print the json nodes to get the format you want. 换句话说,您需要序列化并漂亮地打印json节点以获得所需的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.