Skip to content

Instantly share code, notes, and snippets.

@abhi2495
Last active July 19, 2020 20:28
Show Gist options
  • Save abhi2495/971de7553b026095ca0df74a0171147b to your computer and use it in GitHub Desktop.
Save abhi2495/971de7553b026095ca0df74a0171147b to your computer and use it in GitHub Desktop.
/*
##################################################################################
##################################################################################
######### IF YOU FOUND THIS GIST USEFUL, PLEASE LEAVE A STAR. THANKS. ############
##################################################################################
##################################################################################
*/
String content = FileUtils.readFileToString(new File("src/main/resources/sample.json"), "UTF-8");
DocumentContext jsonContext = JsonPath.parse(content);
jsonContext.delete("$.reservations[*].customers");
jsonContext.renameKey("$.reservations[*]","id","reservations.id");
System.out.println(jsonContext.jsonString());
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
{
"reservations":[
{
"id":"1318504",
"deposit":720,
"rooms":[
{
"name":"room1",
"id":"28902"
},
{
"name":"room2",
"id":"28906"
}
],
"customers":[
{
"id":3,
"country":"UK",
"firstName":"John"
}
]
},
{
"id":"1318501",
"deposit":68,
"rooms":[
{
"name":"room3",
"id":"28860"
},
{
"name":"room4",
"id":"28886"
}
]
}
]
}

A simple example to remove/manipulate json nodes is by using JsonPath

{
"reservations":[
{
"deposit":720,
"rooms":[
{
"name":"room1",
"id":"28902"
},
{
"name":"room2",
"id":"28906"
}
],
"reservations.id":"1318504"
},
{
"deposit":68,
"rooms":[
{
"name":"room3",
"id":"28860"
},
{
"name":"room4",
"id":"28886"
}
],
"reservations.id":"1318501"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment