Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving dictionary into json python

I am quite new to python and I was trying to make two arrays or matrices, register them into a dictionary, save to a json file. Here is my code

import numpy as np
import json
array_1 = np.array([[1,2,3],[4,6,7]])
array_2 = np.array([[4,0],[9,8]])
json_data = {
    'array_1': array_1,
    'array_2': array_2,
 }

import json

with open('json_data.json', 'wb') as fp:
    json.dumps(json_data, fp)

But I get the following error:

Object of type 'ndarray' is not JSON serializable

like image 701
StudentOIST Avatar asked Oct 27 '25 21:10

StudentOIST


1 Answers

First convert it to the python list like this:

json_data = {
    'array_1': array_1.tolist(),
    'array_2': array_2.tolist()
 }

and then try to dump it as a json:

import json

with open('json_data.json', 'w') as fp:
    json.dump(json_data, fp)
like image 71
mdegis Avatar answered Oct 29 '25 10:10

mdegis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!