Skip to content
Advertisement

How to select the complete JSON node if any key-value pair matched inside the node?

I have JSON some thing like below

{
    "title": "seller_information",
    "sellers": [
        {
            "seller": "s1",
            "prod_on_sale": "flowers"
        },
        {
            "seller": "s2",
            "prod_on_sale": "pet_food"
        },
        {
            "seller": "s3",
            "prod_on_sale": "vegatables"
        }
    ]
}

I am aware how to iterate through JSON Array based on key and extract the values of that particular key. But stuck with one scenario let say instead of key i have value with if i have value ‘s1’ with me i want to traverse through above JSON and if it matches with any value i want to extract the complete JSON related to that value ‘s1’ like below

 {
   "seller": "s1",
    "prod_on_sale": "flowers"
 }

Please suggest some idea how can i do this i am newbie to JSON. Thanks in advance.

Advertisement

Answer

public static JSONObject getObject(String itemToSearch, JSONArray array) {
    for(int i = 0; i < array.length(); i++) {
        try {
            JSONObject jsonObject = array.getJSONObject(i);
            if (jsonObject.getString("seller").equals(itemToSearch)){
                return jsonObject;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return null;
}

you can use this function by sending array of sellers from your JSON

sellersArray = yourJSON.getJSONArray("sellers");
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement