Creating A Pandas DataFrame From A JSON String


  • JSON is the abbreviation of JavaScript Object Notation. A JSON string consists of a collection of name value pairs. The value for a name can be a collection.
  • The function read_json() of pandas library constructs and returns a DataFrame object, while to_json() creates a JSON string from a DataFrame object.


# Example Python program that creates
# a DataFrame instance from a JSON string
import pandas as pds

# Animal data as JSON string
animalData = """[{"Animal":"Asian Elephant", "Height": 110, "Weight":8818}, 
                 {"Animal":"Lion", "Height": 47, "Weight":418}, 
                 {"Animal":"Giraffe", "Height": 232, "Weight":2627}, 
                 {"Animal":"Brush Rabbit", "Height": 12, "Weight":1.54}]"""
# Create a DataFrame from JSON              
animalDataFrame = pds.read_json(animalData)

# Print the DataFrame


           Animal  Height   Weight

0  Asian Elephant     110  8818.00

1            Lion      47   418.00

2         Giraffe     232  2627.00

3    Brush Rabbit      12     1.54


Copyright 2022 ©