Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
user3181411 Avatar asked Jan 30 '14 09:01

user3181411


People also ask

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

How do I dump a JSON file?

Another way of writing JSON to a file is by using json. dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

What is the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

What does JSON dump return?

dumps() takes in a json object and returns a string.


2 Answers

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)
like image 58
senshin Avatar answered Nov 01 '22 23:11

senshin


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)
like image 34
Waqas Avatar answered Nov 02 '22 00:11

Waqas