itsource

JSON 개체는 str, 바이트 또는 byearray여야 하며 dict가 아닙니다.

mycopycode 2023. 4. 2. 10:24
반응형

JSON 개체는 str, 바이트 또는 byearray여야 하며 dict가 아닙니다.

Python 3에서 이전에 저장된 json을 로드하려면 다음과 같이 하십시오.

json.dumps(dictionary)

출력은 다음과 같습니다.

{"('Hello',)": 6, "('Hi',)": 5}

사용할 때

json.loads({"('Hello',)": 6, "('Hi',)": 5})

동작하지 않고, 다음과 같은 일이 발생합니다.

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

json.loads문자열을 입력으로 사용하고 사전을 출력으로 반환합니다.

json.dumps사전을 입력으로 사용하고 문자열을 출력으로 반환합니다.


와 함께json.loads({"('Hello',)": 6, "('Hi',)": 5}),

전화하고 있습니다.json.loads사전이 입력되어 있습니다.

다음과 같이 수정할 수 있습니다(요점이 무엇인지 잘 모르겠습니다).

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)
import json
data = json.load(open('/Users/laxmanjeergal/Desktop/json.json'))
jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output.
dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output.
print(dict_json["shipments"])

문자열을 필요로 하는 함수에 사전을 전달하고 있습니다.

다음 구문:

{"('Hello',)": 6, "('Hi',)": 5}

는 유효한 Python 딕셔너리 리터럴과 유효한 JSON 오브젝트 리터럴입니다.그렇지만loads는 사전을 사용하지 않고 문자열을 사용합니다.이 문자열은 JSON으로 해석되어 결과를 사전(또는 문자열, 배열 또는 숫자, JSON에 따라 다르지만 일반적으로 사전)으로 반환합니다.

이 문자열을 전달하면loads:

'''{"('Hello',)": 6, "('Hi',)": 5}'''

그런 다음 전달하려는 사전과 매우 유사한 사전을 반환합니다.

또한 다음과 같이 함으로써 JSON 객체 리터럴과 Python 사전 리터럴의 유사성을 이용할 수 있습니다.

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))

하지만 어느 경우든 전달하고 있는 사전을 돌려받을 수 있기 때문에 어떤 결과를 얻을 수 있을지 잘 모르겠습니다.당신의 목표는 무엇입니까?

json.dumps() JSON 데이터를 디코딩하는 데 사용됩니다.

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

출력:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python 개체에서 JSON으로 데이터 변환
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() JSON 데이터를 Python 데이터로 변환하는 데 사용됩니다.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

출력:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON 데이터를 Python 개체로 변환
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

최근에 JSON 파일을 직접 읽다가 이 문제에 직면했어요.json 파일을 읽고 파싱하는 동안 이 문제에 직면한 사람이 있으면 여기에 제출합니다.

jsonfile = open('path/to/file.json','r')
json_data = json.load(jsonfile)

loads() 대신 load()를 사용했습니다.

Django REST 프레임워크 작업 중에 이 오류가 발생했습니다.Postgre를 사용했습니다.네이티브 함수를 사용하여 구축된 SQL 구체화 뷰json_build_object.기능으로 바꾸자 오류가 사라졌습니다.jsonb_build_object.

언급URL : https://stackoverflow.com/questions/42354001/json-object-must-be-str-bytes-or-bytearray-not-dict

반응형