Search code examples
pythonjsongroovyjsonslurper

Pull key from json file when values is known (groovy or python)


Is there any way to pull the key from JSON if the only thing I know is the value? (In groovy or python) An example: I know the "_number" value and I need a key. So let's say, known _number is 2 and as an output, I should get dsf34f43f34f34f

{
  "id": "8e37ecadf4908f79d58080e6ddbc",
  "project": "some_project",
  "branch": "master",
  "current_revision": "3rtgfgdfg2fdsf",
  "revisions": {
    "43g5g534534rf34f43f": {
      "_number": 3,
      "created": "2019-04-16 09:03:07.459000000",
      "uploader": {
        "_account_id": 4
      },
      "description": "Rebase"
    },
    "dsf34f43f34f34f": {
      "_number": 2,
      "created": "2019-04-02 10:54:14.682000000",
      "uploader": {
        "_account_id": 2
      },
      "description": "Rebase"
    }
  }
}

Solution

  • With Groovy:

    def json = new groovy.json.JsonSlurper().parse("x.json" as File)
    println(json.revisions.findResult{ it.value._number==2 ? it.key : null })
    // => dsf34f43f34f34f