python JSON object must be str, bytes or bytearray, not 'dict

后端 未结 3 1283
梦如初夏
梦如初夏 2020-12-07 17:29

In Python 3, to load json previously saved like this:

json.dumps(dictionary)

the output is something like

{\"(\'Hello\',)\": 6, \"

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 18:09

    You are passing a dictionary to a function that expects a string.

    This syntax:

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

    is both a valid Python dictionary literal and a valid JSON object literal. But loads doesn't take a dictionary; it takes a string, which it then interprets as JSON and returns the result as a dictionary (or string or array or number, depending on the JSON, but usually a dictionary).

    If you pass this string to loads:

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

    then it will return a dictionary that looks a lot like the one you are trying to pass to it.

    You could also exploit the similarity of JSON object literals to Python dictionary literals by doing this:

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

    But in either case you would just get back the dictionary that you're passing in, so I'm not sure what it would accomplish. What's your goal?

提交回复
热议问题