i was trying to remove json node from json file. For parsing ande getting not i used 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));
}
here it is removing ith node of children.But when i checked in the json file i could see change is not happend ? println(Children.get(i)); is displaying next node after the removed one .and count also is decremented .so how will i save the file after removing the child node ?
You don't say what your JSON looks like, so I've had a guess... I put:
{ "roots":{
"bookmark_bar":{
"children":[
{ "name":"Google", "url":"http://www.google.com" },
{ "name":"StackOverflow", "url":"http://stackoverflow.com" }
]
}
}
}
into /tmp/test.json
And then running this script:
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 }
Changes the file contents to:
{
"roots": {
"bookmark_bar": {
"children": [
{
"name": "StackOverflow",
"url": "http://stackoverflow.com"
}
]
}
}
}
Is that what you wanted?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With