我试图从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));
}
Run Code Online (Sandbox Code Playgroud)
这里它删除了孩子们的第i个节点.但是当我在json文件中检查时,我发现变化不会发生?的println(Children.get(I)); 在删除后的节点后显示下一个节点.计数也递减.那么在删除子节点后如何保存文件?
tim*_*tes 10
你没有说出你的JSON是什么样的,所以我猜错了...我把:
{ "roots":{
"bookmark_bar":{
"children":[
{ "name":"Google", "url":"http://www.google.com" },
{ "name":"StackOverflow", "url":"http://stackoverflow.com" }
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
成 /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 }
Run Code Online (Sandbox Code Playgroud)
将文件内容更改为:
{
"roots": {
"bookmark_bar": {
"children": [
{
"name": "StackOverflow",
"url": "http://stackoverflow.com"
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
那是你想要的吗?
归档时间: |
|
查看次数: |
4734 次 |
最近记录: |