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

后端 未结 3 1278
梦如初夏
梦如初夏 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条回答
  • 2020-12-07 17:57
    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"])
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-12-07 18:15

    json.loads take a string as input and returns a dictionary as output.

    json.dumps take a dictionary as input and returns a string as output.


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

    You are calling json.loads with a dictionary as input.

    You can fix it as follows (though I'm not quite sure what's the point of that):

    d1 = {"('Hello',)": 6, "('Hi',)": 5}
    s1 = json.dumps(d1)
    d2 = json.loads(s1)
    
    0 讨论(0)
提交回复
热议问题