[英]Python : Access a JSON element
Here is a sample of my Json file:这是我的 Json 文件的示例:
{ '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.load ,
json.loads it is used when your json is in a string, bytes or bytearray json.loads当您的 json 在字符串、字节或字节数组中时使用它
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:您可以使用dict
理解对每个单词的向量值使用 map 的字典:
word_vect = {d['word']: d['vector'] for d in data_dict['data']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.