Hussain ali
Hussain ali

Reputation: 522

Write json in the file from list of json

I am calling one API several times to get the result. The result is returned in json format. I am saving all the results in a list. Once all the data is received then I write the content of the list to a file using the following code. My end goal is to save the results in a file with valid json. However the following code adds '\' to the json result in file. Can someone please help me solve the issue.

result = []
// In a for loop I append json results to this list. I have not written the code here.
// Then I use this code to write to a file.
with open(host_log_path, 'w') as log_file:
    log_file.write(json.dumps(result))

sample current output with slashes:

["{\"hdr\":{\"msgt\":\"InitialState\",\"ver\":\"CV-NOTSET\",\"uid\":1,\"seq\":1}}"]

Upvotes: 0

Views: 1314

Answers (1)

Barmar
Barmar

Reputation: 780724

The output you're getting indicates that result contains a list of JSON strings, not a list of objects. You don't need to call json.dumps(), they're already formatted as JSON. You should just write each of them as a separate line in the log file.

with open(host_log_path, "a") as log_file:
    for msg in result:
        log_file.write((msg if type(msg) is str else json.dumps(msg)) + "\n")

You also should use a mode to append to the log file. Your code clears out the old contents each time yuo open it.

If you want to write them as a single JSON array, you can call json.loads() in the loop.

with open(host_log_path, "w") as log_file:
    msgs = [json.loads(msg) if type(msg) is str else msg for msg in result]
    json.dump(msgs, log_file)

Upvotes: 1

Related Questions