如何使用groovy基于excel表数据从JSON获取节点对象或数组?

时间:2018-01-09 11:55:36

标签: json api groovy

假设我有以下JSON: -

{
  "book": [

  {
     "id": "01",
     "language": "Java",
     "edition": "third",
     "author": "Herbert Schildt"
  },

  {
     "id": "07",
     "language": "C++",
     "edition": "second",
     "author": "E.Balagurusamy"
  }

  ]
}

而且,我从excel表中传递了作者的价值,以检查作者是否存在。如果该作者存在于JSON内部,那么该特定数组节点仅存在并从JSON中删除其他节点。

例如: - 我正在过去"作者"价值为" Herbert Schildt"来自excel表。现在这个值存在于JSON中,所以,我需要打印这个特定的数组节点,并且应该删除所有数据节点。像这样: -

{
"book": [
 {
 "id": "01",
 "language": "Java",
 "edition": "third",
 "author": "Herbert Schildt"
  }
]
}

可以用groovy完成吗?我尝试过使用HashMap,但无法通过。

2 个答案:

答案 0 :(得分:1)

使用groovy很容易:

def text = '''{
  "book": [

  {
     "id": "01",
     "language": "Java",
     "edition": "third",
     "author": "Herbert Schildt"
  },

  {
     "id": "07",
     "language": "C++",
     "edition": "second",
     "author": "E.Balagurusamy"
  }

  ]
}
'''

def result = groovy.json.JsonOutput.toJson(
 [book: new groovy.json.JsonSlurper().parseText(text).book.findAll{it.author == "Herbert Schildt"}]
)

println result

答案 1 :(得分:0)

您可以尝试这种方式json搜索

var json = '{"book":[{"id":"01","language":"Java","edition":"third","author":"Herbert Schildt"},{"id":"07","language":"C++","edition":"second","author":"E.Balagurusamy"}]}';
var parsed = JSON.parse(json);
var result = {};
result.book = [];
var author = "Herbert Schildt";
parsed.book.map((i, j) =>  {
	if(i.author == author) {
		
		result.book.push(i);
	}
});

console.log(result)