saving dictionary into json python

Viewed 11421

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

3 Answers

First correct your data. Correct data: json_data = { 'array_1': array_1, 'array_2': array_2 }

There is a extra ',' at the end of the line (array_2). That is the reason you are getting JSON serialization issue.

Related