samarth
samarth

Reputation: 4024

Using jq to compare two fields from same json and printing some other field as a result

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

Answers (2)

RomanPerekhrest
RomanPerekhrest

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 comparison

Upvotes: 10

Ashish Kumar
Ashish Kumar

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

Related Questions