简体   繁体   中英

How can I get array values from key in json file with python?

Here is my JSON file:

{"name": "Nghia", "name2": ["Bao", "Tam"]}

My Python code:

file = open(jsonfile, 'r')
data = json.load(file)
key = list(data.keys())
value = list(data.values())
print(key[value.index('Nghia')])

Output: name

But the issue is I can't use key[value.index('Bao')] or key[value.index('Tam')] to get name2

In simple terms, the index() method finds the given element in a list and returns its position.

So here,

key = list(data.keys()) // ['name', 'name2']
value = list(data.values()) // ['Nghia', ['Bao', 'Tam']]

Now this code

print(key[value.index('Nghia')])

finds the element from this list ['Nghia', ['Bao', 'Tam']] and returns the index of that element and print it.

So above you can see in the second element of the list ['Nghia', ['Bao', 'Tam']], we have an array as element ['Bao', 'Tam']

So in order to find the the index of that element in the value list, you have to use this

print(key[value.index(['Bao', 'Tam'])]) 

here is the function which returns the index of an element if the element in the list is an array or string

Function takes two arguments value and item, value is a List item is the element of list which index needs to be find

Function returns -1 if its not found any item in the list

def findIndex(value,item):
    for elementIndex in range(0, len(value)):
        if type(value[elementIndex]) is list:
            for itemElemIndex in range(0 ,len(value[elementIndex])):
                if value[elementIndex][itemElemIndex] == item:
                    return elementIndex    
        else:
            if value[elementIndex] == item:
                return elementIndex
    return -1
print(key[findIndex(value,"Tam")])

The issue is that you're trying to match a string to a list, which will of course not match. If you must keep the structure of your data, you need to explicitly check for both strings matching or the list containing the string. For example:

data = {"name": "Nghia", "name2": ["Bao", "Tam"]}

search_term = "Bao"

for k, v in data.items():
  if v == search_term or search_term in v:
    print("Found in " + k)
  else :
    print("Not found in " + k)

which will output

Not found in name
Found in name2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM