python JSON对象必须是str,bytes或bytearray,而不是'dict

dil*_*a93 30 python json dictionary

在Python 3中,加载之前保存的json如下:

json.dumps(dictionary)

输出是这样的

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

我用的时候

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

它不起作用,发生这种情况:

TypeError:JSON对象必须是str,bytes或bytearray,而不是'dict'

bar*_*nos 53

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)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@barak manos 这真的很有帮助。我有一个返回数据,它是 `json.loads(data)` 。当我使用 `json.dumps(loadedData)` 解码时摆脱了上述错误并设法通过 `object_hook` 将其转换为 python 对象。 (2认同)

小智 14

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"])
Run Code Online (Sandbox Code Playgroud)


Mar*_*eed 8

您正在将字典传递给需要字符串的函数。

这个语法:

{"('Hello',)": 6, "('Hi',)": 5}
Run Code Online (Sandbox Code Playgroud)

是有效的Python字典文字和有效的JSON对象文字。但是loads不带字典。它接受一个字符串,然后将其解释为JSON并字典(或字符串,数组或数字,具体取决于JSON,但通常是字典)。

如果将此字符串传递给loads

'''{"('Hello',)": 6, "('Hi',)": 5}'''
Run Code Online (Sandbox Code Playgroud)

然后它将返回一本看起来很像您要传递给它的字典的字典。

您还可以通过执行以下操作来利用JSON对象文字与Python字典文字的相似性:

json.loads(str({"('Hello',)": 6, "('Hi',)": 5}))
Run Code Online (Sandbox Code Playgroud)

但是无论哪种情况,您都只会取回您要传递的字典,所以我不确定它会完成什么。你的目标是什么?


小智 6

嘿,我最近在直接读取 JSON 文件时遇到了这个问题。如果有人在读取 json 文件然后解析它时遇到此问题,请将其放在这里:

jsonfile = open('path/to/file.json','r')
json_data = json.load(jsonfile)
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了 load() 而不是 load()。


Mil*_*vić 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
Run Code Online (Sandbox Code Playgroud)

输出:

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
        ]
    ]
}
Run Code Online (Sandbox Code Playgroud)
  • Python 对象到 JSON 数据的转换
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |
Run Code Online (Sandbox Code Playgroud)

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'])
Run Code Online (Sandbox Code Playgroud)

输出:

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]
Run Code Online (Sandbox Code Playgroud)
  • JSON 数据到 Python 对象的转换
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |
Run Code Online (Sandbox Code Playgroud)