tags:

views:

18

answers:

1

Hi, I am looking query the JSON data based on some where conditions for ex. list the person names whose cell no is 777-777-7777.

pl let me know what are query capabilities in JSON.

var json = [{ "name": "senthil",
    "Phoneno": [{ "Home": "111-111-1111" },
                        { "Cell": "222-222-2222" },
                        { "Office": "333-333-3333" }
                        ],
    "City": "Hartford"
    },
    { "name": "kumar",
        "Phoneno": [{ "Home": "444-555-6666" },
                        { "Cell": "777-777-7777" },
                        { "Office": "888-888-8888" }
                        ],
        "City": "Austin"
    },
    ];
+1  A: 
var people = json.filter(function(el) 
             { 
               return el.Phoneno.some(function(number) 
                      {
                        return number.Cell == "777-777-7777"; 
                      }); 
             });

This uses the Array.filter and Array.some functions from ECMAScript 5. filter returns an array of the elements that pass a test. some returns true if any element in an array passes the test.

For browsers that don't support it, you can use the code at MDC.

This will almost certainly not be faster than the obvious for-loop approach.

As a note, if every person can have up to one phone number per type, a simpler representation would be:

"Phoneno": { "Home": "111-111-1111",
             "Cell": "222-222-2222",
             "Office": "333-333-3333" 
           }

Also, JSON technically refers to the text representation, not actual JavaScript objects.

Matthew Flaschen