[英]Groovy script: How to parse/format Json in groovy in each loop
我是Groovy的新手,我想在soap ui中模拟服务。
要求是使用json数据加载文本文件,并使用匹配数据加载节点。
我尝试过的如下
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
}
}
}
格式很完美,只是一个问题。 当ID1加载到requestContext.Id中时,json格式将从文件中丢失。
我需要的是
{
"items" {
"number" : 1475175072691
}
}
我得到的是
{
metadata = {
timestamp = 1475175072691
}
}
为什么从我的json中删除双引号“和冒号: 。请提出建议。
如下代码:
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))
}
打印出以下结果:
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
{
"items": {
"number": 1475175072691
}
}
换句话说,您需要序列化并漂亮地打印json节点以获得所需的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.