tatintat
tatintat

Reputation: 13

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

Upvotes: 1

Views: 131

Answers (1)

kederrac
kederrac

Reputation: 17322

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']}

Upvotes: 1

Related Questions