Python 将 numpy.nd 数组转换为 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43346300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:54:42  来源:igfitidea点击:

Convert numpy.nd array to json

pythonarraysjsonnumpy

提问by Nayana Madhu

I've a data frame genre_rail in which one column contains numpy.ndarray. The dataframe looks like as given belowdatframe

我有一个数据框genre_rail,其中一列包含numpy.ndarray. 数据框如下所示数据框

The array in it looks like this :

其中的数组如下所示:

['SINGTEL_movie_22906' 'SINGTEL_movie_22943' 'SINGTEL_movie_24404'
 'SINGTEL_movie_22924' 'SINGTEL_movie_22937' 'SINGTEL_movie_22900'
 'SINGTEL_movie_24416' 'SINGTEL_movie_24422']

I tried with the following code

我尝试使用以下代码

import json
json_content = json.dumps({'mydata': [genre_rail.iloc[i]['content_id'] for i in range(len(genre_rail))] })

But got an error

但是出错了

TypeError: array is not JSON serializable

类型错误:数组不是 JSON 可序列化的

I need output as

我需要输出为

{"Rail2_contend_id":
["SINGTEL_movie_22894","SINGTEL_movie_22898",
"SINGTEL_movie_22896","SINGTEL_movie_24609","SINGTEL_movie_2455",
"SINGTEL_movie_24550","SINGTEL_movie_24548","SINGTEL_movie_24546"]}

回答by Fadil Olamyy Wahab

How about you convert the array to json using the .tolistmethod. Then you can write it to json like :

您如何使用该.tolist方法将数组转换为 json 。然后你可以把它写成 json 像:

np_array_to_list = np_array.tolist()
json_file = "file.json" 
json.dump(b, codecs.open(json_file, 'w', encoding='utf-8'), sort_keys=True, indent=4)

回答by Bhuvan Kumar

Load all the data in dictionary, then dump it to json. Below code might help you

将所有数据加载到字典中,然后将其转储到 json。下面的代码可能对你有帮助

import json

#Data
d = ['SINGTEL_movie_22906', 'SINGTEL_movie_22943', 'SINGTEL_movie_24404'
 'SINGTEL_movie_22924', 'SINGTEL_movie_22937', 'SINGTEL_movie_22900'
 'SINGTEL_movie_24416', 'SINGTEL_movie_24422']

#Create dict
dic = {}
dic['Rail2_contend_id'] = d

print dic

#Dump data dict to jason
j = json.dumps(dic)

Output

输出

{'Rail2_contend_id': ['SINGTEL_movie_22906', 'SINGTEL_movie_22943', 'SINGTEL_movie_24404SINGTEL_movie_22924', 'SINGTEL_movie_22937', 'SINGTEL_movie_22900SINGTEL_movie_24416', 'SINGTEL_movie_24422']}

{'Rail2_contend_id':['SINGTEL_movie_22906','SINGTEL_movie_22943','SINGTEL_movie_24404SINGTEL_movie_22924','SINGTEL_movie_22937',4SINGTEL_movie_22937'22937'SINGTEL_movie_22937'22937'SINGTEL_movie_22943'SINGTEL_movie_22943'SINGTEL_movie_22937'SINGTEL_movie_22937'SINGTEL_movie_22937'SINGTEL_movie_6SINGTEL_6SINGTEL_6