Reputation: 4024
I have json data in following format
{
"body": [
{
"username": "name1",
"id": "4444"
},
{
"username": "name2",
"id": "5555"
}
],
"meta": {
"input": "name1"
}}
Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.
Upvotes: 7
Views: 8216
Reputation: 92854
jq solution:
jq '.meta.input as $meta | .body[] | select(.username == $meta).id' input.json
The output:
"4444"
.meta.input as $meta
- assigning .meta.input
key value to $meta
variable for further comparisonUpvotes: 10
Reputation: 3039
This should be as simple as that:
var data = {
"body": [{
"username": "name1",
"id": "4444"
}, {
"username": "name2",
"id": "5555"
}],
"meta": {
"input": "name1"
}
};
function getID(data) {
var username = data.meta.input;
var userID;
for (i in data.body) {
if (data.body[i].username === username) {
userID = data.body[i].id;
break;
}
}
return userID;
}
var id = getID(data);
alert(id);
Upvotes: -1