-2

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"
    }
  }
}
Kristianmitk
  • 4,528
  • 5
  • 26
  • 46

3 Answers3

0

Python 3: (assuming that data is saved in data.json):

import json

with open('data.json') as f:
    json_data = json.load(f)

for rev, revdata in json_data['revisions'].items():
    if revdata['_number'] == 2:
        print(rev)

Prints all revs where _number equals 2.

Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
0

using dict-comprehension:

print({k for k,v in d['revisions'].items() if v.get('_number') == 2})

OUTPUT:

{'dsf34f43f34f34f'}
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

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
cfrick
  • 35,203
  • 6
  • 56
  • 68