Reputation: 135
I want to remove age from this json file using org.json
or com.googlecode.json-simple
?
Suppose this json objects are in a file test.json?
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
After removing the file test.json should be.
{
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
Please tell me how to take out the json object out of the json file?
Upvotes: 3
Views: 8063
Reputation: 19
I tried the same but my output is different.
JSONObject getJsonResp = (JSONObject)obj; getJsonResp.remove("messages")
Original JSON{"name":"ALK","messages":["msg 1","msg 2","msg 3"],"age":100} After Removing ["msg 1","msg 2","msg 3"]
Upvotes: 0
Reputation: 768
This will traverse all of the top-most keys of the Json object, and remove those that pass condition.
try {
JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader("test.json"));
Set keys = jsonObject.keySet();
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
if (key.equals("age")) {
System.out.println("REMOVING KEY:VALUE")
System.out.println(key + ":" + jsonObject.get(key).toString());
iterator.remove();
jsonObject.remove(key);
}
}
try (FileWriter file = new FileWriter("test.json")) { //store data
file.write(jsonObject.toJSONString());
file.flush();
}
} catch (IOException | ParseException ex) {
System.out.println("Error: " + ex);
}
iterator.remove() MUST come before jsonObject.remove(key)
Upvotes: 2
Reputation: 36703
Read from file and parse
Path file = Paths.get("test.json");
String input = new String(Files.readAllBytes(file), StandardCharsets.UTF_8);
JSONObject obj = (JSONObject) JSONValue.parse(input);
Remove the key you don't want, note JSONObject implements java.util.Map...
obj.remove("age");
Encode as as String and write back to the file
String output = JSONValue.toJSONString(obj);
Files.write(file, output.getBytes(StandardCharsets.UTF_8));
Input
{"age":100,"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"]}
Output
{"name":"mkyong.com","messages":["msg 1","msg 2","msg 3"]}
Upvotes: 2