user3181411
user3181411

Reputation: 145

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 doesn't dumps the data into the "file.json" file. When I write print before json.dumps(), then the data gets printed on the screen. But it doesn't get dumped into the file.

The file gets created but on opening it (using notepad), there is nothing. Why?

How to correct it?

Upvotes: 6

Views: 22472

Answers (4)

Silver
Silver

Reputation: 141

Also check that your output file path is a relative path.

output_json_path = '../Desktop/test_folder/test.json' #This works
# output_json_path = '~/Desktop/test_folder/test.json' #This does not work
with open(output_json_path, 'w+', encoding='utf8') as f:
    json.dump({l1 : tagging_dictionary}, f, ensure_ascii = False)

Upvotes: 0

Waqas
Waqas

Reputation: 3853

Simply,

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)

Upvotes: 1

senshin
senshin

Reputation: 10360

This isn't how json.dumps() works. json.dumps() returns a string, which you must then write into the file using f.write(). Like so:

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

Or, just use json.dump(), which exists exactly for the purpose of dumping JSON data into a file descriptor.

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

Upvotes: 9

gioi
gioi

Reputation: 1483

You need to use json.dump. json.dumps returns a string, it doesn't write to a file descriptor.

Upvotes: 0

Related Questions