Why is my file not being recorded in JSON

Question:

    news_dict[article_id] = {
        "article_date_timestamp": article_date_timestamp,
        "article_title": article_title,
        "article_url": article_url,
        "article_desc": article_desc
    }

with open("news_dict.txt", 'w') as file:
    json.dump(news_dict, file, indent=4, ensure_ascii=False)

The json entry does not work.

Asked By: Python1177

||

Answers:

try using

if __name__ == "__main__":
    main()
Answered By: SCcagg5

I’ve made simple solution which works based on your snippet. You can try with this. To your code I’ve added default=str in json_dump()

import json
from datetime import datetime
news_dict = {}

article_id = 1
article_date_timestamp = datetime.now()
article_title = "Title"
article_url = "http://example.com"
article_desc = "Description"


news_dict[article_id] = {
    "article_date_timestamp": article_date_timestamp,
    "article_title": article_title,
    "article_url": article_url,
    "article_desc": article_desc
    }


with open("news_dict.json", 'w') as file:
    json.dump(news_dict, file, indent=4, ensure_ascii=False, default=str)
Answered By: Faekr
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.