skip to Main Content

Not sure if it is possible. I want multiply the "value" field with the "lvalue" field an put the result in a new field "calc" in the corresponding array entry.

Given JSON:

{
  "value": 5,
  "location": [{
    "city": "San Fracisco",
    "lvalue": 10
  },
  {
    "city": "Los Angeles",
    "lvalue": 20
  }]
}

Expected Value in one JSON:

{
  "value": 5,
  "location": [{
    "city": "San Fracisco",
    "lvalue": 10,
    "calc": 50
  },
  {
    "city": "Los Angeles",
    "lvalue": 20,
    "calc": 100
  }]
}

2

Answers


  1. Chosen as BEST ANSWER

    Is there also a solution if the value to multiply itself is in an array? In this example multiply lvalue from outer location array with value from inner cities value.

    Given JSON:

    {
      "country": "USA",
      "location": [{
        "city": "San Fracisco",
        "lvalue": 1,
        "cities": [{
           "type":"city",
           "value": 10
        }]
      },
      {
        "city": "Los Angeles",
        "lvalue": 2,
        "cities": [{
           "type":"city",
           "value": 10
        }]
      }]
    }
    

    Expected Value in one JSON:

    {
      "country": "USA",
      "location": [{
        "city": "San Fracisco",
        "lvalue": 1,
        "cities": [{
           "type":"city",
           "value": 10,
           "calc": 10
        }]
      },
      {
        "city": "Los Angeles",
        "lvalue": 2,
        "cities": [{
           "type":"city",
           "value": 10,
           "calc": 20
        }]
      }]
    }
    

  2. You need to ‘save’ the .value in a variable before looping over the locations to update them using |=:

    .value as $val | .location[] |= (.calc = $val * .lvalue)
    

    JqPlay Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search