Lutfor
Lutfor

Reputation: 307

Returning parent by Parsing JSON object

What will be Javascript code look like in following scenario? I have following json object.

  jsonObject=  '{
     "2lor": {"userID":"1","clientID":"abc123","uid":"j42d"},
     "WFAR": {"userID":"2","clientID":"xyz123","uid":"V23d"}
    }'

I want to parse above json. I want to return

"2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}

when my parameter is "j42d".

My function will be look like this one.

function Find(uid, done) {

  return done(null, value);
};

uid: "j42d", value(output):

"2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}

Upvotes: 2

Views: 311

Answers (2)

Cameron Edwards
Cameron Edwards

Reputation: 198

You'll need to loop over your JSON object and find the values that fit your criteria.

And Pamblam is right, you need to either get rid of the linebreaks in your string, or build your JSON as an object literal:

var json = {  
  "2lor":{  
    "userID":"1",
    "clientID":"abc123",
    "uid":"j42d"
  },
  "WFAR":{  
    "userID":"2",
    "clientID":"xyz123",
    "uid":"V23d"
  }
};
var myResult = getByUid(json, "j42d");

function getByUid(data, uid) {
    for (var key in data) {
        if (data.hasOwnProperty(key) && data[key].uid === uid) {
            var obj = {};
            obj[key] = data[key];
            return obj;
        }
    }
    return {};
}

Upvotes: 1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

var json_string = '{ "2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}, "WFAR": {"userID":"2","clientID":"xyz123","uid":"V23d"} }';
var json = JSON.parse(json_string);
var data = json['2lor'];

// to get the uid..
var uid = data.uid;

Note, you can't have linebreaks in javascript strings unless you escape them, so you will need to put that all on one line (or just remove the outer quotes and skip the parsing).

Upvotes: 1

Related Questions