Pandas DataFrame - Convert row to JSON


Pandas DataFrame - Convert row to JSON

In Pandas, to convert a row in a DataFrame to a JSON string, you can use to_json() method.

Each row of a DataFrame can be accessed as a Series object, and Series objects have a method to_json() that returns the JSON string representation of the row (Series object).

The syntax to use to_json() method to convert a DataFrame row to a JSON string is

row.to_json()

In this tutorial, we will go through some examples, with step by step explanation of how to convert a given row in DataFrame to a JSON string.

Examples

1. Convert row in given DataFrame to JSON

In this example, we are given a DataFrame in df_input. We have to convert the second row in this DataFrame to a JSON string.

Steps

  1. Given a DataFrame in df_input with three columns 'A', 'B', and 'C', and five rows.
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [10, 20, 30, 40, 50]})
  1. Select the second row, and store it in a variable.
row = df_input.iloc[1]
  1. Call to_json() method on row series object, and store the returned JSON string value in a variable row_json.
row_json = row.to_json()
  1. You may print the JSON string to output using print() function.
print(row_json)

Program

The complete program to convert a row in a given DataFrame to a JSON string.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6, 8, 10],
    'B': [1, 3, 5, 7, 9],
    'C': [10, 20, 30, 40, 50]})

# Select row
row = df_input.iloc[1]

# Convert row to JSON string
row_json = row.to_json()

# Print the JSON string
print(row_json)

Output

{"A":4,"B":3,"C":20}

The column labels of DataFrame have become the filed names in the JSON object, and the row values for each column of the DataFrame have become the values in the JSON object.

Summary

In this Pandas Tutorial, we learned how to convert a given row in a DataFrame to a JSON string using to_json() method, with examples.