Json.dumps () not working

import json

def json_serialize(name, ftype, path):

        prof_info = []

        prof_info.append({
            'profile_name': name,
            'filter_type': ftype
        })

        with open(path, "w") as f:
            json.dumps({'profile_info': prof_info}, f)

json_serialize(profile_name, filter_type, "/home/file.json")

The above code does not upload data to file.json. When I write printto json.dumps(), then the data is printed on the screen. But it does not get into the file.

The file is created, but when you open it (using notepad), there is nothing. Why?

How to fix it?

+4
source share
3 answers

This does not work json.dumps(). json.dumps()returns a string that you must write to the file with f.write(). For example:

with open(path, 'w') as f:
    json_str = json.dumps({'profile_info': prof_info})
    f.write(json_str)

Or just use json.dump()that exists precisely to dump JSON data into a file descriptor.

with open(path, 'w') as f:
    json.dump({'profile_info': prof_info}, f)
+5
source

json.dump. json.dumps , .

0

,

import json

my_list = range(1,10) # a list from 1 to 10

with open('theJsonFile.json', 'w') as file_descriptor:

         json.dump(my_list, file_descriptor)
0

Source: https://habr.com/ru/post/1524460/


All Articles