0

Below is what I have as JSON String.

{
    "ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
    "ROW_INFO":{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
    "ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}

What I want is to get the JSONObject which have ID as ID_A i.e. ID_A0001 & ID_A0002.

I was thinking of using jsonObject.getString("ID_A"), but that is not possible. Could someone tell me what should I do so that I will get as below output.

{
    "ID_A0001":{"areaID":"A0001","shopID":"SH004","quantity":14},
    "ID_A0002":{"areaID":"A0002","shopID":"SH008","quantity":18}
}

2 Answers 2

4

The following code does what you want, assuming the object you posted is stored in obj. In case you actually have a JSON string instead of an object, use JSON.parse() to convert the string to a JavaScript object.

var obj2 = {};
for(var key in obj) {
    if(key.substr(0, 4) == 'ID_A') {
        obj2[key] = obj[key];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

In the json object you have mentioned, you can modifiy it as follows.

 var jsontest={
    ID_A0001:{"areaID":"A0001","shopID":"SH004","quantity":14},
    ROW_INFO:{"areaID":"VARCHAR","shopID":"VARCHAR","quantity":"INT"},
    ID_A0002:{"areaID":"A0002","shopID":"SH008","quantity":18}
        };

for(var key in jsontest) {
    if(key.substring(0,4)=='ID_A')
    alert('key: ' + key + '\n' + 'value: ' + jsontest[key].areaID);
}

http://jsfiddle.net/FBLvP/

Here is a useful link which shows us how to get the list of keys from a json object http://encosia.com/using-jquery-1-6-to-find-an-array-of-an-objects-keys/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.