Home > Software engineering >  why is my file not being recorded in json, please help me
why is my file not being recorded in json, please help me

Time:11-09

enter code here
    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)

#help me #the json entry does not work, please help

CodePudding user response:

Could you provide an error which occurs when you run your program? 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