相关文章推荐
开朗的枇杷  ·  Java ...·  14 小时前    · 
从容的圣诞树  ·  java 把Set<Object>转成 ...·  14 小时前    · 
着急的黄瓜  ·  Set<Object>强转为Set<Stri ...·  14 小时前    · 
气势凌人的苦咖啡  ·  XGBoost - ...·  7 月前    · 
开心的炒饭  ·  C++ ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

json.dumps(dictionary)

the output is something like

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

when I use

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

it doesn't work, this happens:

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'
                Looks like you already are dealing with the actual dictionary and not a string. How are you reading in the data you dumped?
– gosuto
                Feb 11, 2018 at 9:42

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)
                Thanx @barak manos this really helped. I had a return data which was json.loads(data) . when I decode that using json.dumps(loadedData) get rid of the above error and manage to convert that to a python object by object_hook .
– Tharusha
                Jan 25, 2018 at 11:24
                To simplify, you can directly convert: d1 = {"('Hello',)": 6, "('Hi',)": 5}   and them  d2 = json.loads(json.dumps(d1))
– Waldeyr Mendes da Silva
                Apr 19, 2022 at 17:58
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"])

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?

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

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
        "normal string",
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
    "nested list": [
            "normal string",
  • Python Object to JSON Data Conversion
  • |                 Python                 |  JSON  |
    |:--------------------------------------:|:------:|
    |                  dict                  | object |
    |               list, tuple              |  array |
    |                   str                  | string |
    | int, float, int- & float-derived Enums | number |
    |                  True                  |  true  |
    |                  False                 |  false |
    |                  None                  |  null  |
    

    json.loads() is used to convert JSON data into Python data.

    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'])
    

    output:

    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 Data to Python Object Conversion
  • |      JSON     | Python |
    |:-------------:|:------:|
    |     object    |  dict  |
    |     array     |  list  |
    |     string    |   str  |
    |  number (int) |   int  |
    | number (real) |  float |
    |      true     |  True  |
    |     false     |  False |
    

    Hey I recently faced this issue while reading the JSON file directly. Just putting it out here if anyone faces this issue while reading json file and then parsing it:

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

    Notice that I used load() instead of loads().

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.