Convert json fake news file to csv python
Here is an example of how you can convert a JSON file containing fake news data to a CSV file using Python:
import json
import csv
# Load the JSON file
with open('fake_news.json') as f:
data = json.load(f)
# Create a CSV writer
with open('fake_news.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
# Write the header row
writer.writerow(['title', 'text', 'source', 'date'])
# Write each news article to the CSV file
for article in data:
writer.writerow([article['title'], article['text'], article['source'], article['date']])
This code assumes that your JSON file has the following structure:
[
{
"title": "Fake News Article 1",
"text": "This is the text of the article",
"source": "Fake News Source 1",
"date": "2022-01-01"
},
{
"title": "Fake News Article 2",
"text": "This is the text of the article",
"source": "Fake News Source 2",
"date": "2022-01-02"
},
...
]
And that you want to convert it to a CSV file with the following structure:
title,text,source,date
Fake News Article 1,This is the text of the article,Fake News Source 1,2022-01-01
Fake News Article 2,This is the text of the article,Fake News Source 2,2022-01-02
...
You can adjust the code to match the structure of your JSON file and the desired output of your CSV file.
Also, you can use pandas
library to achieve this, it's more efficient and easy to use:
import pandas as pd
data = pd.read_json('fake_news.json')
data.to_csv('fake_news.csv', index=False)
This will create a CSV file with the same structure as the JSON file, and it will be more efficient than the previous example.