我试图从json文件中删除json节点。对于解析ande得到的不是我使用json slurper
File f=new File(fileLocation);
def result = new JsonSlurper().parseText(f.text)
Map jsonResult = (Map) result;
Map Bookmarkbar = (Map) jsonResult.get("roots").get("bookmark_bar");
List Children=(List) Bookmarkbar.get("children");
println("no of elements "+Children.get(i).size());
if("Google".equals(Children.get(i).get("name"))
{
Children.remove(i);
println(Children.get(i));
}
这里是删除子节点的第i个节点。但是当我在json文件中检查时,我可以看到更改没有发生?的println(Children.get(I));在删除后的节点后显示下一个节点。计数也递减。那么在删除子节点后如何保存文件?
答案 0 :(得分:10)
你没有说出你的JSON是什么样的,所以我猜错了......我说:
{ "roots":{
"bookmark_bar":{
"children":[
{ "name":"Google", "url":"http://www.google.com" },
{ "name":"StackOverflow", "url":"http://stackoverflow.com" }
]
}
}
}
进入/tmp/test.json
然后运行此脚本:
import groovy.json.*
File jsonFile = new File( '/tmp/test.json' )
// Load the Json into a Map
Map result = new JsonSlurper().parseText( jsonFile.text )
// Set the children to every element whos name isn't Google
result.roots.bookmark_bar.children = result.roots.bookmark_bar.children.findAll {
it.name != 'Google'
}
// Get the new JSON string
String newJson = new JsonBuilder( result ).toPrettyString()
// And write it out to the file again
jsonFile.withWriter( 'UTF-8' ) { it << newJson }
将文件内容更改为:
{
"roots": {
"bookmark_bar": {
"children": [
{
"name": "StackOverflow",
"url": "http://stackoverflow.com"
}
]
}
}
}
这就是你想要的吗?