Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask question.(5)

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

ITtutoria

ITtutoria Logo ITtutoria Logo

ITtutoria Navigation

  • Python
  • Java
  • Reactjs
  • JavaScript
  • R
  • PySpark
  • MYSQL
  • Pandas
  • QA
  • C++
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA
Home/ Questions/The complete guide to the ''typeerror object of type ndarray is not json serializable'' issue.
Next
Answered
James O'Kelly
  • 15
James O'Kelly
Asked: May 18, 20222022-05-18T17:58:23+00:00 2022-05-18T17:58:23+00:00In: python

The complete guide to the ”typeerror object of type ndarray is not json serializable” issue.

  • 15

. Advertisement .

..3..

. Advertisement .

..4..

Hi everyone, I’m learning about python. While working, I try load the webpage after creating a NumPy array, and saving it as a Django context variable. As a result, I get the message:

array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64) is not JSON serializable

What can I do about the “typeerror object of type ndarray is not json serializable” issue? Is there a better approach?

typeerror
  • 2 2 Answers
  • 139 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook
  • Report

2 Answers

  • Voted
  • Oldest
  • Recent
  • Random
  1. Best Answer
    lyytutoria Expert
    2022-06-29T01:19:47+00:00Added an answer on June 29, 2022 at 1:19 am

    The cause:

    The error happens because you are attempting to change a NumPy ndarray object into a JSON string but the default function which is called for objects can not be serialized, so it raises an error.

    Solution:

    You can solve this problem by applying “.tolist()” method for the first arrays as the below:

    import numpy as np
    import codecs, json
    
    a = np.arange(10).reshape(2,5) # a 2 by 5 array
    b = a.tolist() # nested lists with the similar data, indices
    file_path = "/path.json" ## your path variable
    json.dump(b, codecs.open(file_path, 'w', encoding='utf-8'),
    separators=(',', ':'),
    sort_keys=True,
    indent=4) ### the array is saved in .json format by this

    Next, let’s use these following commands to “unjsonify” the array:

    obj_text = codecs.open(file_path, 'r', encoding='utf-8').read()
    b_new = json.loads(obj_text)
    a_new = np.array(b_new)
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
  2. Ambre Morand
    2022-05-25T20:42:56+00:00Added an answer on May 25, 2022 at 8:42 pm

    Save as JSON a numpy.ndarray and any other nested-list component.

    class NumpyEncoder(json.JSONEncoder):
     def default(self, obj):
     if isinstance(obj, np.ndarray):
     return obj.tolist()
     return json.JSONEncoder.default(self, obj)
    
    a = np.array([[1, 2, 3], [4, 5, 6]])
    print(a.shape)
    json_dump = json.dumps({'a': a, 'aa': [2, (2, 3, 4), a], 'bb': [2]}, 
     cls=NumpyEncoder)
    print(json_dump)

    What will output look like?

    (2, 3)
    {"a": [[1, 2, 3], [4, 5, 6]], "aa": [2, [2, 3, 4], [[1, 2, 3], [4, 5, 6]]], "bb": [2]}

    To restore using JSON:

    json_load = json.loads(json_dump)
    a_restored = np.asarray(json_load["a"])
    print(a_restored)
    print(a_restored.shape)

    What will output look like?

    [[1 2 3]
     [4 5 6]]
    (2, 3)
    • 13
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question
  • How to Split String by space in C++
  • How To Convert A Pandas DataFrame Column To A List
  • How to Replace Multiple Characters in A String in Python?
  • How To Remove Special Characters From String Python

Explore

  • Home
  • Tutorial

Footer

ITtutoria

ITtutoria

This website is user friendly and will facilitate transferring knowledge. It would be useful for a self-initiated learning process.

@ ITTutoria Co Ltd.

Tutorial

  • Home
  • Python
  • Science
  • Java
  • JavaScript
  • Reactjs
  • Nodejs
  • Tools
  • QA

Legal Stuff

  • About Us
  • Terms of Use
  • Privacy Policy
  • Contact Us

DMCA.com Protection Status

Help

  • Knowledge Base
  • Support

Follow

© 2022 Ittutoria. All Rights Reserved.

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.