国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

解決報錯TypeError: Object of type int32 is not JSON serializable

這篇具有很好參考價值的文章主要介紹了解決報錯TypeError: Object of type int32 is not JSON serializable。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

報錯原因:

當(dāng)我們嘗試將 numpy int32 對象轉(zhuǎn)換為 JSON 字符串時,會出現(xiàn) Python“TypeError: Object of type int32 is not JSON serializable”。 要解決該錯誤,請先將 numpy int 轉(zhuǎn)換為 Python 整數(shù),然后再將其轉(zhuǎn)換為 JSON,例如

int(my_numpy_int)

解決方案:

下面是錯誤如何發(fā)生的示例。

import json
import numpy as np

salary = np.power(50, 2, dtype=np.int32)

# ?? TypeError: Object of type int32 is not JSON serializable
json_str = json.dumps({'salary': salary})

我們嘗試將 numpy int32 對象傳遞給 json.dumps() 方法,但該方法默認(rèn)不處理 numpy integers。

要解決該錯誤,請在序列化之前使用內(nèi)置的 int()或 float()函數(shù)將 numpy int32 對象轉(zhuǎn)換為Python integer。

import json
import numpy as np

salary = np.power(50, 2, dtype=np.int32)

# ? convert to Python native int
json_str = json.dumps({'salary': int(salary)})

print(json_str)  # ??? '{"salary": 2500}'
print(type(json_str))  # ??? <class 'str'>

默認(rèn)的 JSON 編碼器處理 int 和 float 值,因此我們可以在序列化為 JSON 時使用原生 Python int 而不是 numpy int32。

json.dumps 方法將 Python 對象轉(zhuǎn)換為 JSON 格式的字符串。

或者,您可以從 JSONEncoder 類擴(kuò)展并在默認(rèn)方法中處理轉(zhuǎn)換。

import json
import numpy as np


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)


salary = np.power(50, 2, dtype=np.int32)

json_str = json.dumps({'salary': salary}, cls=NpEncoder)

print(json_str)  # ??? {"salary": 2500}
print(type(json_str))  # ??? <class 'str'>

我們從 JSONEncoder 類擴(kuò)展而來。

JSONEncoder 類默認(rèn)支持以下對象和類型。

Python JSON
dict object
list, tuple array
str string
int, float, int and float derived Enums number
True true
False false
None null

請注意,默認(rèn)情況下,JSONEncoder 類不支持 numpy int32 到 JSON 的轉(zhuǎn)換。?

我們可以通過從類擴(kuò)展并實(shí)現(xiàn)返回可序列化對象的 default() 方法來處理這個問題。

import json
import numpy as np


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

如果傳入的對象是 np.integer 的實(shí)例,我們將對象轉(zhuǎn)換為 Python int 并返回結(jié)果。

如果傳入的對象是 np.floating 的實(shí)例,我們將其轉(zhuǎn)換為 Python float 并返回結(jié)果。

如果對象是 np.ndarray 的實(shí)例,我們將其轉(zhuǎn)換為 Python list并返回結(jié)果。

在所有其他情況下,我們讓基類的默認(rèn)方法進(jìn)行序列化。

要使用自定義 JSONEncoder,請在調(diào)用 json.dumps() 方法時使用 cls 關(guān)鍵字參數(shù)指定它。

import json
import numpy as np


class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        if isinstance(obj, np.floating):
            return float(obj)
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)


salary = np.power(50, 2, dtype=np.int32)

# ? provide cls keyword argument
json_str = json.dumps({'salary': salary}, cls=NpEncoder)

print(json_str)  # ??? {"salary": 2500}
print(type(json_str))  # ??? <class 'str'>

如果您不提供 'cls'?kwarg,則使用默認(rèn)的 JSONEncoder。

?文章來源地址http://www.zghlxwxcb.cn/news/detail-457188.html

到了這里,關(guān)于解決報錯TypeError: Object of type int32 is not JSON serializable的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Django去訪問web api接口Object of type Session is not JSON serializable

    解決方案:settings.py中加入 :SESSION_SERIALIZER = \\\'django.contrib.sessions.serializers.PickleSerializer\\\' 事由:Django去訪問一個web api接口,兩次連接之間需要通過Session()保持身份驗證。 加入SESSION_SERIALIZER = \\\'django.contrib.sessions.serializers.PickleSerializer\\\' 后解決。 ?

    2024年02月04日
    瀏覽(15)
  • python常見錯誤-TypeError: ‘int‘ object is not iterable

    可能大家在Python編程過程中經(jīng)常會遇到? ?TypeError: \\\'int\\\' object is not iterable? ?的錯誤。這是因為我們嘗試迭代一個整數(shù)對象,但Python無法迭代整數(shù)。 這個錯誤經(jīng)常是用for循環(huán)迭代整數(shù)。例如以下代碼: 運(yùn)行以上代碼會得到以下錯誤信息:TypeError: \\\'int\\\' object is not iterable 要解

    2024年04月14日
    瀏覽(33)
  • Stable Diffusion圖生圖報錯TypeError: argument of type ‘NoneType‘ is not iterable如何解決?

    Stable Diffusion圖生圖報錯TypeError: argument of type ‘NoneType‘ is not iterable如何解決?

    之前運(yùn)行都沒事,突然莫名開始報錯,試了很多方法找不到原因,求大神指路~ ? ?

    2024年02月04日
    瀏覽(26)
  • pip報TypeError: ‘type‘ object is not subscriptable錯誤

    pip報TypeError: ‘type‘ object is not subscriptable錯誤

    因為安裝 Manim庫,中間下載 colour 組件時因為更新pip版本到 23.1.2 ,與python3.9.0 適配的 pip version 19.2.3 版本矛盾,導(dǎo)致后續(xù)無法正常使用python,出現(xiàn)如下報錯: 修復(fù) pip 的思路很簡單,出問題的并不是 python ,而是因為 pip 的版本等級太高,因此想辦法能夠把 pip 的版本降低就可

    2024年02月15日
    瀏覽(24)
  • python 報錯TypeError: object of type ‘NoneType‘ has no len()處理

    在編程過程中,我們經(jīng)常會遇到各種異常情況。其中之一就是TypeError異常,它表示操作或函數(shù)應(yīng)用于了錯誤的數(shù)據(jù)類型。在本文中,我們將重點(diǎn)討論TypeError異常中的一種常見情況:當(dāng)對象為NoneType時,調(diào)用len()函數(shù)會引發(fā)TypeError異常。 在Python中,NoneType是一個特殊的數(shù)據(jù)類型,

    2024年02月06日
    瀏覽(21)
  • python 報錯TypeError: ‘float‘ object is not callable

    python 報錯TypeError: ‘float‘ object is not callable

    python公式中少打了乘號“*”,如下圖所示 一般是變量名與函數(shù)沖突,如本文中前面代碼用到sum,后面直接用sum()函數(shù)同樣報錯,下圖: 檢查公式是否少打“*”號,python中對格式要求比較嚴(yán)格,不能直接用數(shù)學(xué)中省略符號的算式 調(diào)用函數(shù),sum()函數(shù)用np.sum()函數(shù) python報

    2024年02月10日
    瀏覽(24)
  • 成功解決TypeError: ‘<‘ not supported between instances of ‘str‘ and ‘int‘

    成功解決TypeError: \\\'\\\' not supported between instances of \\\'str\\\' and \\\'int\\\' 目錄 解決問題 解決思路 解決方法 TypeError: \\\'\\\' not supported between instances of \\\'str\\\' and \\\'int\\\' 類型錯誤:\\\'\\\'在\\\'str\\\'和\\\'int\\\'實(shí)例之間不支持

    2024年02月14日
    瀏覽(20)
  • 【Python】成功解決TypeError: object of type ‘numpy.float64‘ has no len()

    【Python】成功解決TypeError: object of type ‘numpy.float64‘ has no len()

    【Python】成功解決TypeError: object of type ‘numpy.float64’ has no len() ?? 個人主頁:高斯小哥 ?? 高質(zhì)量專欄:Matplotlib之旅:零基礎(chǔ)精通數(shù)據(jù)可視化、Python基礎(chǔ)【高質(zhì)量合集】、PyTorch零基礎(chǔ)入門教程?? 希望得到您的訂閱和支持~ ?? 創(chuàng)作高質(zhì)量博文(平均質(zhì)量分92+),分享更多關(guān)于

    2024年04月17日
    瀏覽(52)
  • TypeError: ‘float‘ object is not subscriptable 已解決

    TypeError: ‘float‘ object is not subscriptable 已解決

    其實(shí)就是個小問題,但是爆出來的時候也很莫名其妙。因為之前都跑得好好的,只是換了不同的文件去跑才出的問題,關(guān)鍵是不同的文件要處理的內(nèi)容和格式都是完全一樣的,一個順利跑完,一個就報TypeError: ‘float’ object is not subscriptable這個錯,就非常無語。接下來就是看

    2024年02月11日
    瀏覽(35)
  • 【已解決TypeError: ‘dict‘ object is not callable】

    【已解決TypeError: ‘dict‘ object is not callable】

    情況1: 取字典內(nèi)容的時候使用的是() 解決: 將()改為[ ] 情況2: 原來已經(jīng)定義過dict函數(shù),此時想使用python內(nèi)置函數(shù)就會報錯 可以看到如果我們先定義一個dict,那內(nèi)置函數(shù)就會報錯。 解決: 將之前定義的dict函數(shù)刪掉 刪除方法:你可以直接刪掉函數(shù)重新運(yùn)行,也可以

    2024年02月15日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包