Creating a pandas DataFrame from a JSON String

JSON stands for JavaScript Object Notation. The Python example creates a pandas DataFrame object from a JSON string and prints the output to the console.

Serialization Updated 16 Nov 2021 1 min read

Overview

  • 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
# 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

            print(animalDataFrame)

Output

Output
           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