I've a data frame genre_rail in which one column contains numpy.ndarray
. The dataframe looks like as given below
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
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"]}
Use the cls kwarg of the json. dump() and json. dumps() method to call our custom JSON Encoder, which will convert NumPy array into JSON formatted data. To serialize Numpy array into JSON we need to convert it into a list structure using a tolist() function.
Practical Data Science using Python We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array. We can check the type of numpy array using the dtype class.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.
Python's NumPy array can be used to serialize and deserialize data to and from byte representation.
How about you convert the array to json using the .tolist
method.
Then you can write it to json like :
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)
Load all the data in dictionary, then dump it to json. Below code might help you
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With