4

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

1
  • The json module only knows how to serialize native Python types like list, dict, etc. You will need to either store your arrays as Python lists in your json_data dictionary, or write a function that is called by json.dumps to do the conversion automatically. Read about the default parameter to json.dumps. Commented Sep 16, 2017 at 10:52

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

3 Comments

It gives me the following error: dumps() takes 1 positional argument but 2 were given
i can only make it work with with open('json_data.json', 'w') as fp: json.dump(json_data, fp)
@smvpfm: json.dumps() dumps to a string. Use json.dump() instead.
1

The best and easiest way of doing this is:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

2 Comments

No, it doesn't work: TypeError: Object of type 'ndarray' is not JSON serializable
You need to deal with ndarray first. It's an unique data type
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.