/ / Salvando arquivo após remover o json node - json, groovy

Salvando arquivo após remover o json node - json, groovy

Eu estava tentando remover o nó json do arquivo json. Para a análise ee recebendo não eu usei 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));
}

aqui está removendo o nó dos filhos.Mas quando eu chequei no arquivo JSON eu podia ver a mudança não é happend? println (Children.get (i)); está exibindo o próximo nó após o removido. e a contagem também é diminuída. por isso, como salvarei o arquivo após remover o nó filho?

Respostas:

8 para resposta № 1

Você não diz qual é o seu JSON, então eu tive um palpite ... eu coloquei:

{ "roots":{
"bookmark_bar":{
"children":[
{ "name":"Google", "url":"http://www.google.com" },
{ "name":"StackOverflow", "url":"http://stackoverflow.com" }
]
}
}
}

para dentro /tmp/test.json

E então executando este 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 }

Altera o conteúdo do arquivo para:

{
"roots": {
"bookmark_bar": {
"children": [
{
"name": "StackOverflow",
"url": "http://stackoverflow.com"
}
]
}
}
}

É isso que você queria?