복붙노트

[PYTHON] json.dumps (np.arange (5) .tolist ())가 작동하는 동안 json.dumps (list (np.arange (5)))가 실패하는 이유는 무엇입니까?

PYTHON

json.dumps (np.arange (5) .tolist ())가 작동하는 동안 json.dumps (list (np.arange (5)))가 실패하는 이유는 무엇입니까?

우분투를 실행하는 컴퓨터가 최근에 업데이트되었고 Python의 기본 버전이 2.7로 변경되었을 때이 문제가 나타났습니다.

import json
import numpy as np

json.dumps(list(np.arange(5))) # Fails, throws a "TypeError: 0 is not JSON serializable"
json.dumps(np.arange(5).tolist()) # Works 

numpy 배열의 list ()와 tolist () 메소드 사이에 차이점이 있습니까?

해결법

  1. ==============================

    1.tolist () 메서드는 numpy int32 (또는 사용자가 가지고있는 크기)를 다시 int로 변환하는 것으로 보입니다. JSON은이를 처리 할 수 ​​있습니다.

    tolist () 메서드는 numpy int32 (또는 사용자가 가지고있는 크기)를 다시 int로 변환하는 것으로 보입니다. JSON은이를 처리 할 수 ​​있습니다.

    >>> list(np.arange(5))
    [0, 1, 2, 3, 4]
    >>> type(list(np.arange(5)))
    <type 'list'>
    >>> type(list(np.arange(5))[0])
    <type 'numpy.int32'>
    >>> np.arange(5).tolist()
    [0, 1, 2, 3, 4]
    >>> type(np.arange(5).tolist())
    <type 'list'>
    >>> type(np.arange(5).tolist()[0])
    <type 'int'>
    

    docs가 tolist ()에 대해 말하는 것처럼 :

    마지막 줄이 여기서 차이를 만듭니다.

  2. ==============================

    2.NumPy 배열의 요소는 native int가 아니고 NUmPy의 자체 유형이기 때문에 :

    NumPy 배열의 요소는 native int가 아니고 NUmPy의 자체 유형이기 때문에 :

    >>> type(np.arange(5)[0])
    <type 'numpy.int64'>
    

    사용자 정의 JSONEncoder를 사용하여 arange가 반환 한 ndarray 유형을 지원할 수 있습니다.

    import numpy as np
    import json
    
    class NumPyArangeEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist() # or map(int, obj)
            return json.JSONEncoder.default(self, obj)
    
    print(json.dumps(np.arange(5), cls=NumPyArangeEncoder))
    
  3. ==============================

    3.문제는 처음에는 int를 얻지 못한다는 것입니다. 당신은 멍청 해 .int64. 그것은 직렬화 될 수 없습니다.

    문제는 처음에는 int를 얻지 못한다는 것입니다. 당신은 멍청 해 .int64. 그것은 직렬화 될 수 없습니다.

  4. from https://stackoverflow.com/questions/11561932/why-does-json-dumpslistnp-arange5-fail-while-json-dumpsnp-arange5-tolis by cc-by-sa and MIT license