Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除json节点后保存文件_Json_Groovy - Fatal编程技术网

删除json节点后保存文件

删除json节点后保存文件,json,groovy,Json,Groovy,我试图从json文件中删除json节点。对于解析和获取,我使用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) B

我试图从json文件中删除json节点。对于解析和获取,我使用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));在删除的节点之后显示下一个节点。并且计数也会减少。那么在删除子节点后如何保存文件?

您没有说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 }

这就是您想要的吗?

是的,完全相同,但它会用update保存文件/tmp/test.json吗?@Rajani yes。。最后一行
jsonFile.withWriter('UTF-8'){it@Rajani别担心:-)你介意吗?祝你好运,希望我的代码有意义;-)
{
    "roots": {
        "bookmark_bar": {
            "children": [
                {
                    "name": "StackOverflow",
                    "url": "http://stackoverflow.com"
                }
            ]
        }
    }
}