The Ways to Python Tabulate JSON

Python Tabulate JSON , use the pd.DataFrame() function. pd.DataFrame() is a pandas library function that helps us create two-dimensional, variable-size and potentially heterogeneous tabular data in Python.

The Ways to Python Tabulate JSON

JSON stands for JavaScript Object Notation. It is somewhat similar to a Python dictionary. The JSON data type is mainly used in web applications to exchange data between the client and the server.

A JSON object contains values, and we can convert these values ​​into a table using the pandas package. The pandas library provides a function called pd.DataFrame() which will convert these objects into table-like structures.

Program to Python Tabulate JSON using Pandas

import pandas as pd
import json

with open("/Users/krunallathiya/Desktop/Code/R/sample.json") as f:
  d = json.load(f)
  df = pd.DataFrame(columns=d[0].keys())
   for i in range(len(d)):
     df.loc[i] = d[i].values()

In this program, we import json and pandas packages. The json package is for working with json data, and the pandas package is for converting the json object into a table, which you can call a dataframe.

We opened a json file that contained all the content that needed to be converted into a table. Next, we have opened the sample.json file. It contains json objects.

Then we load the json data from the file into a variable called d . Now this variable d contains json objects. In Python, JSON objects are treated like a dictionary. Therefore, it consists of key-value pairs. Key is the name of the column and value is the value of that field.

Also read:- The 5 Best Website to Practice Your Front End skills

We create a data frame with columns as json object keys. The dict.keys() function extracts all the keys individually from the dictionary. So if we run this function, all the keys of the json object will be extracted. These keys are given as column names of the data frame.

We traverse the JSON object and add each row to a data frame. Hence a table is formed we can print data frame to see the result.

Complete Python Program of Tabulate JSON in Python

import json
import pandas as pd

json_data = [
 {'userId': 1,
 'number': 45,
 'name': 'Raj'},
 {'userId': 2,
 'number': 46,
 'name': 'Ram'},
 {'userId': 3,
 'number': 47,
 'name': 'Rahu'}

with open("sample.json", "w") as f:
  json.dump(json_data, f)

with open("sample.json", "r") as f:

with open("sample.json") as f:
  d = json.load(f)
  df = pd.DataFrame(columns=d[0].keys())
  for i in range(len(d)):
    df.loc[i] = d[i].values()


[{'userId': 1, 'number': 45, 'name': 'Raj'}, {'userId': 2, 'number': 46, 'name': 'Ram'}, 
 {'userId': 3, 'number': 47, 'name': 'Rahu'}]

  userId number  name

0   1     45     Raj
1   2     46     Ram
2   3     47     Rahu

Making Game with iteration game design

Also read:7 Best FREE YouTube Video Downloader Apps 

Leave a Comment