1

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'))

2
  • What do you mean by "index?" Do you want the position inside the actual, full JSON text? Or are you looking for the list index after parsing the JSON and looping over it? Commented Nov 4, 2020 at 17:34
  • Yes sorry i should mention it becomes a list when the file is imported Commented Nov 4, 2020 at 17:36

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

8 Comments

You could also use enumerate() here instead of a position variable. Like: for position, item in enumerate(data):
What if i dont' know that the key is google, how can i test just for 'FEB4F' ?
@Uriel Do you need to get what the key is? Or do you just want the position? If you just want the position, then you can try if 'FEB4F' in item.values():.
@Uriel You mean the dict at the position you've found? That would be data[position].
Or just item.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.