How to convert JSON to Pandas DataFrame in Python
In this article, we will study how to convert JSON to Pandas DataFrame in Python.
DataFrame stores the data. It aligns the data in tabular fashion. Hence, it is a 2-dimensional data structure.
JSON refers to JavaScript Object Notation. JSON stores and exchange the data. Hence, JSON is a plain text. In Python, JSON is a built-in package. A JSON file is a file that stores data in JavaScript Object Notation (JSON) format. JSON is easy to understand.
Let us create JSON file. Open a file and write the json code. Save this file with json extension. Look at the following code:
{ "Registration No": { "0":"R01", "1":"R02", "2":"R03", "3":"R04" }, "Name": { "0":"Ram", "1":"Shruti", "2":"Sneha", "3":"Shrey" }, "Occupation":{ "0":"Software Developer", "1":"PHP Developer", "2":"C.A", "3":"Clerk" }, "Salary":{ "0":67000, "1":78000, "2":53000, "3":35000 } }
Let’s save this code in a file as “json_file.json”.
Conversion of JSON to Pandas DataFrame in Python
Let us now see how to convert json to pandas DataFrame using Python.
(i) read_json()
The read_json() function converts JSON string to pandas object. It takes several parameters. However, if we simply want to convert Json to DataFrame we just have to pass the path of file. It’s syntax is as follow:
Pandas.read_json(path=None, orient=None, typ=’frame’, dtype=None, convert_axes=None,date_unit=None, convert_dates=True,encoding=None,keep_default_dates=True, numpy=False, compression=’infer’,precise_float=False, lines=False, chunksize=None)
- path- It is the path of the file.
Here we are using the above one.
Look at the following code:
import pandas as pd df = pd.read_json("json_file.json") print(df)
OUTPUT
Registration No Name Occupation Salary 0 R01 Ram Software Developer 67000 1 R02 Shruti PHP Developer 78000 2 R03 Sneha C.A 53000 3 R04 Shrey Clerk 35000
In the above example, “pd” stands for Pandas. Pandas is an open source library of Python. Pandas allows us to create data and perform data manipulation. To use this package, we have to import pandas in our code. The name of the file where json code is present is passed to read_json(). In our example, json_file.json is the name of file. In this way, we can convert JSON to DataFrame.
You may also read: How to add new column to the existing DataFrame
Hey, i saw your article its good. it’s just will be better if u used `df.head()` to print table instead of just this rows ? it just my thoughts! 🙂
Hello, I came across your article through DuckDuckGo search but what I was actually looking for is how to convert a TXT file that contains JSON data, to a Pandas DataFrame. For instance, a json file which was stored in txt format needs to be converted to pandas Dataframe. If you update the article, kindly let me know on instagram, username is “dru.ayo”
Thanks.