如何从json文件中删除json对象? [英] how to remove a json object from a json file?

查看:421
本文介绍了如何从json文件中删除json对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从此json文件using org.jsoncom.googlecode.json-simple中删除年龄吗?

I want to remove age from this json file using org.json or com.googlecode.json-simple?

假设此json对象位于文件test.json中?

Suppose this json objects are in a file test.json?

    {
        "age":100,
        "name":"mkyong.com",
        "messages":["msg 1","msg 2","msg 3"]
    }

删除文件test.json后应该是.

After removing the file test.json should be.

    {
        "name":"mkyong.com",
        "messages":["msg 1","msg 2","msg 3"]
    }

请告诉我如何从json文件中取出json对象?

Please tell me how to take out the json object out of the json file?

推荐答案

这将遍历Json对象的所有最顶层的键,并删除那些通过条件的键.

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()必须位于jsonObject.remove(key)

iterator.remove() MUST come before jsonObject.remove(key)

这篇关于如何从json文件中删除json对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆