0

JSON object as below. Need to find the value based on user input. The input will look like "data.location.type", or "data.location.items[1].address.street". Can it be done in JQuery?

{
    "data": {
        "location": {
            "type": "List",
            "count": 1,
            "items": [
                {
                    "id": 1,
                    "type": "S",
                    "address": {
                        "street": "123 Main St",
                        "city": "New York",
                        "state": "NY"
                    }
                },
                {
                    "id": 2,
                    "type": "S",
                    "address": {
                        "street": "1323 South St",
                        "city": "New York",
                        "state": "NY"
                    }
                }
            ]
        }
    }
}
41
  • 1
    You don't need jQuery for this, plain JS will do the trick. (And by the way, there's no such thing as a JSON object.) Commented Oct 17, 2013 at 21:02
  • 1
    @Chris Sure. But, jQuery defines very little for regular Objects, leaving most of that to core ECMAScript and focusing mostly on DOM. The point is just that jQuery isn't much help here. Commented Oct 17, 2013 at 21:07
  • 1
    @Chris: jQuery is NOT a superset of JavaScript. JavaScript is a language. Technically, JavaScript is an implementation and superset of ECMAScript. jQuery is just a code library. It has no language additions. It's an important distinction. Commented Oct 17, 2013 at 21:08
  • 2
    You could not do this in jQuery because it would require you to use javascript's API. The jQuery API does not support this. Where in the jQuery API is the function that says give me an object and a string and I will return a value? If that exists then you can do this with jQuery, and if it does not, then you cannot. It is very straightforward and that is the nature of APIs. Can the API for Math manipulate the DOM? Then no, you cannot manipulate the DOM with Math. Commented Oct 17, 2013 at 21:38
  • 2
    @Chris comes home from the grocery store with a bag of cookies. Chris' wife says, "What's this? I sent you to get sugar, eggs, etc..." Chris replies "Honey, cookies ARE sugar, eggs, etc...". Chris sleeps on the couch that night. Commented Oct 17, 2013 at 21:46

2 Answers 2

2

First you're going to need to parse it to an object then use an object lookup function like the one below (here's a fiddle of it in action http://jsfiddle.net/C8zH2/):

//https://gist.github.com/megawac/6162481#file-underscore-lookup-js
var lookup = function(obj, key) {
    var type = typeof key;
    if (type == 'string' || type == "number") key = ("" + key).replace(/\[(.*?)\]/, function(m, key){//handle case where [1] may occur
        return '.' + key;
    }).split('.');
    for (var i = 0, l = key.length, currentkey; i < l; i++) {
        if (obj.hasOwnProperty(key[i])) obj = obj[key[i]];
        else return undefined;
    }
    return obj;
}

//syntax: lookup(jsonobj, input);
//Tests using your data
lookup(data, "data.location.type") //=> "List"
lookup(data, "data.location.items[1].address.street") //=> ""1323 South St"
Sign up to request clarification or add additional context in comments.

14 Comments

How does that lookup function resolve the subscript (items[1])? I don't see that in there, it's just looking for '.'
Ya I didnt actually handle that case
Then you should remove the items.1.address as well, it won't behave as stated in your comment
@lethal-guitar Yeah I just checked and it will because its calling items["1"]
That's right, missed that. Doesn't really help the OP anyway. Another thing: There is an extraneous closing brace here: [i])) It should be just one
|
1

This is just thrown together, but it should work for you...

http://jsfiddle.net/E2hEh/2/

var input = "data.location.type";
//var input = "data.location.items[1].address.street";
var parts = input.split('.');

var prev;
for(var i = 0; i < parts.length; i++){
    var index;
    if(parts[i].indexOf('[') != -1){
        var key = parts[i].substr(0, parts[i].indexOf('['));
        index = parseInt(parts[i].substr(parts[i].indexOf('[') + 1, 1), 10);
        if(!prev){
            prev = test[key][index];
        } else {
            prev = prev[key][index];
        }
    } else { 
        if(!prev){
            prev = test[parts[i]];
        } else {
            prev = prev[parts[i]];
        }

        if(i === parts.length - 1){
            alert(prev);
        }
    }
}

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.