Uriel
Uriel

Reputation: 206

Getting index of a value inside a json file PYTHON

I have a sizable json file and i need to get the index of a certain value inside it. Here's what my json file looks like:

data.json

   [{...many more elements here...
   },
   {
    "name": "SQUARED SOS",
    "unified": "1F198",
    "non_qualified": null,
    "docomo": null,
    "au": "E4E8",
    "softbank": null,
    "google": "FEB4F",
    "image": "1f198.png",
    "sheet_x": 0,
    "sheet_y": 28,
    "short_name": "sos",
    "short_names": [
      "sos"
    ],
    "text": null,
    "texts": null,
    "category": "Symbols",
    "sort_order": 167,
    "added_in": "0.6",
    "has_img_apple": true,
    "has_img_google": true,
    "has_img_twitter": true,
    "has_img_facebook": true
  },
  {...many more elements here...
  }]

How can i get the index of the value "FEB4F" whose key is "google", for example?

My only idea was this but it doesn't work: print(data.index('FEB4F'))

Upvotes: 1

Views: 1376

Answers (2)

Arthur Harduim
Arthur Harduim

Reputation: 192

Assuming your data can fit in an table, I recommend using pandas for that. Here is the summary:

IE:

import pandas as pd

data = pd.read_json("path_to_json.json")
print(data)

#lets assume you want to filter using the 'unified' column
filtered = data.loc[data['unified'] == 'something']
print(filtered)

Of course the steps would be different depending on the JSON structure

Upvotes: 0

John Gordon
John Gordon

Reputation: 33335

Your basic data structure is a list, so there's no way to avoid looping over it.

Loop through all the items, keeping track of the current position. If the current item has the desired key/value, print the current position.

position = 0
for item in data:
    if item.get('google') == 'FEB4F':
        print('position is:', position)
        break
    position += 1

Upvotes: 2

Related Questions