Home > Enterprise >  Why is my file not being recorded in JSON
Why is my file not being recorded in JSON

Time:11-09

    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.

CodePudding user response:

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)

CodePudding user response:

try using

if __name__ == "__main__":
    main()
  • Related