简体   繁体   中英

Python : Access a JSON element

Here is a sample of my Json file:

{ 'data':[{'word':'first_word',
           'vector':[[0.4][0.2][0.8] } ,
          {'word':'second_word',
           'vector':[[0.2][0.65][0.7] }
          ]}

I want to access to values of a given word and its vector, and store it in a variable. Here's what I did:

with open('./Vectors.json') as json_file:
    data_dict = json.loads(json_file)
    for word in words: 
        vector = data_dict["Data"][0][w]["vector"]

It returns to me the following error:

TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper

you have to use json.load ,

json.loads it is used when your json is in a string, bytes or bytearray

with open('./Vectors.json') as json_file:
    data_dict = json.load(json_file)

you can use a dict to map for each word the vector values using a dictionary comprehension:

word_vect = {d['word']: d['vector'] for d in data_dict['data']}

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