Manoj venk
Manoj venk

Reputation: 863

How to delete JSON Object inside JSON Array based on particular key's value null?

[{"period":"","billing_mode":"checked","price":"1500","bundleid":0,"name":"hello stack","deviceid":"923is3j4","date":"2016-06-23","userid":0,"type":"mobile","strutid":999}]

I have this JSON Array inside which JSON Objects like above were there. I want JSON Objects which has

"period":""

to get deleted.Is it possible?Please help me thanks. P.S:This is for Java not Javascript.

Upvotes: 1

Views: 1328

Answers (2)

Soyab Badi
Soyab Badi

Reputation: 400

See you can do using this way

This is for PHP guy :)

    $json='{"period":"","billing_mode":"checked","price":"1500","packageid":0,"name":"hello stack","subscriberid":"9283is3j4","date":"2016-06-23","serviceid":0,"type":"event","programid":999}';

    $arr = json_decode($json, true);
    unset($arr['period']);
    echo json_encode($arr);

Upvotes: 1

PVR
PVR

Reputation: 915

If you want in java then using java-json.jar you can achieve it as following:

public static void main(String[] args) throws JSONException {

        String s="{\"period\":\"\",\"billing_mode\":\"checked\",\"price\":\"1500\",\"packageid\":0,\"name\":\"hello stack\",\"subscriberid\":\"9283is3j4\",\"date\":\"2016-06-23\",\"serviceid\":0,\"type\":\"event\",\"programid\":999}";

        JSONObject jsonObj = new JSONObject(s);

        JSONArray nameArray = jsonObj.names();

        List<String> keyList = new ArrayList<String>();
        for (int i = 0; i < nameArray.length(); i++) {
            keyList.add(nameArray.get(i).toString());
        }

            for (String key : keyList) {
                if (jsonObj.get(key).equals("")) 
                {
                    jsonObj.remove(key);
                }
            }

        System.out.println(jsonObj.toString());
    }

If we remove a JSON Key While Iterating JSONArray then it will give following exception:

Exception in thread "main" java.util.ConcurrentModificationException

So i have achieved by copying the JSON array into a Java collection and used the JSONObject.names() method to obtain a JSONArray of keys.

Upvotes: 0

Related Questions