Welcome to Foundation of Data Science Laboratory
Welcome to Foundation of Data Science Laboratory
2.1.2 Importing Data from JSON:
o Download a JSON file from the internet.
o Use Python to import the JSON file into a DataFrame.
o Display the first few rows of the DataFrame.
Program
import pandas as pd
import requests
# Step 1: Download the JSON file from the internet
url = 'https://jsonplaceholder.typicode.com/posts' # Example URL of a JSON file
response = requests.get(url)
json_data = response.json()
# Step 2: Import the JSON data into a DataFrame
df = pd.DataFrame(json_data)
# Step 3: Display the first few rows of the DataFrame
print(df.head())
Download the JSON file:
requests.get(url): Sends an HTTP GET request to the specified URL.
response.json(): Converts the JSON response to a Python dictionary/list.
Import JSON data into a DataFrame:
pd.DataFrame(json_data): Converts the JSON data into a Pandas DataFrame.
Display the first few rows:
df.head(): Displays the first 5 rows of the DataFrame by default.
Expected Output:
userId id title \
0 1 1 sunt aut facere repellat provident occaecati e...
1 1 2 qui est esse
2 1 3 ea molestias quasi exercitationem repellat qui ...
3 1 4 eum et est occaecati
4 1 5 nesciunt quas odio
body
0 quia et suscipit\nsuscipit repellat nisi quo e...
1 est rerum tempore vitae\nsequi sint nihil repr...
2 et iusto sed quo iure\nvoluptatem occaecati om...
3 ullam et saepe reiciendis voluptatem adipiscit...
4 repellat provident occaecati excepturi optio r...