Use Series.to_json and if necessary change key value add rename:

print (k.set_index('A').rename(columns={'B':'index1'}).to_json())
{"index1":{"1":"a","2":"b","3":"c","4":"d"}}

If need export to file:

k.set_index('A').rename(columns={'B':'index1'}).to_json('file.json')
Answer from jezrael on Stack Overflow
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.to_json.html
pandas.DataFrame.to_json — pandas 3.0.2 documentation
Will throw ValueError if incorrect ‘orient’ since others are not list-like. ... For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buf’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'xz', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdCompressor, lzma.LZMAFile or tarfile.TarFile, respectively.
Discussions

python - Using column values as key in pandas json - Stack Overflow
I have a pandas dataframe as below. I'm just wondering if there's any way to have my column values as my key to the json. df: |symbol | price| |:------|------| |a. |120| |b. |100| |c ... More on stackoverflow.com
🌐 stackoverflow.com
python - convert pandas dataframe to json with columns as key - Stack Overflow
I have a data frame like this: df: Col1 col2 col3 col4 A 1 2 3 A 4 5 6 A 7 8 9 B 3 2 1 B 4 4 ... More on stackoverflow.com
🌐 stackoverflow.com
March 5, 2019
Convert Pandas DataFrame to JSON format - Stack Overflow
I have a Pandas DataFrame with two columns – one with the filename and one with the hour in which it was generated: File Hour F1 1 F1 2 F2 1 F3 1 I am More on stackoverflow.com
🌐 stackoverflow.com
python - Transform pandas DataFrame to json and add new keys - Stack Overflow
I am not sure how to word this properly, so I will try to explain this with a replicable example. I have thousands of entries in a pandas.DataFrame object. I want to export each row as its own json... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.5 › reference › api › pandas.DataFrame.to_json.html
pandas.DataFrame.to_json — pandas 1.5.3 documentation
Will throw ValueError if incorrect ‘orient’ since others are not list-like. ... For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buf’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdCompressor or tarfile.TarFile, respectively.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 2.0 › reference › api › pandas.DataFrame.to_json.html
pandas.DataFrame.to_json — pandas 2.0.3 documentation
Will throw ValueError if incorrect ‘orient’ since others are not list-like. ... For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buf’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdCompressor or tarfile.TarFile, respectively.
🌐
Spark Code Hub
sparkcodehub.com › pandas-dataframe-to-json-guide
Converting Pandas DataFrame to JSON: A Comprehensive Guide
For an introduction to Pandas, check out Pandas Tutorial Introduction. ... to_json() method as the primary tool for converting a DataFrame to JSON. This method is highly flexible, offering various orientation options and parameters to customize the output. Below, we explore its syntax, key ...
🌐
Statology
statology.org › home › how to convert a pandas dataframe to json
How to Convert a Pandas DataFrame to JSON
July 30, 2020 - ‘values’ : just the values array · ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}} This tutorial shows how to convert a DataFrame to each of the six formats using the following pandas DataFrame: import pandas as pd #create DataFrame df = pd.DataFrame({'points': [25, 12, 15, 19], 'assists': [5, 7, 7, 12]}) #view DataFrame df points assists 0 25 5 1 12 7 2 15 7 3 19 12 · df.to_json(orient='split') { "columns": [ "points", "assists" ], "index": [ 0, 1, 2, 3 ], "data": [ [ 25, 5 ], [ 12, 7 ], [ 15, 7 ], [ 19, 12 ] ] } df.to_json(orient='records') [ { "points": 25, "assis
🌐
Stack Overflow
stackoverflow.com › questions › 72259400 › using-column-values-as-key-in-pandas-json
python - Using column values as key in pandas json - Stack Overflow
If one wants the JSON values as a list, the following will do the work · df.groupby('symbol').price.apply(list).to_json() [Out]: {"a":[120],"b":[100],"c":[200]} ... Sign up to request clarification or add additional context in comments. ... import pandas as pd d = {'symbol': ['a', 'b', 'c'], 'price': [120, 100, 200]} df = pd.DataFrame(data=d) print(df) print (df.set_index('symbol').rename(columns={'price':'json_data'}).to_json()) # EXPORT TO FILE df.set_index('symbol').rename(columns={'price':'json_data'}).to_json('price.json')
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-pandas-dataframe-into-json-in-python
How to convert pandas DataFrame into JSON in Python? - GeeksforGeeks
June 12, 2025 - The to_json() method in Pandas provides a flexible way to convert a DataFrame into different JSON formats. The orient parameter allows you to customize how rows and columns are represented in the output.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › python-pandas-dataframe-to-nested-json
Python Pandas Dataframe To Nested Json - GeeksforGeeks
July 23, 2025 - The most straightforward approach is to use the `to_json` method of pandas, specifying the orientation as 'records'. ... import pandas as pd # Create a sample DataFrame data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35], 'City': ...
🌐
Pandas
pandas.pydata.org › docs › dev › reference › api › pandas.DataFrame.to_json.html
pandas.DataFrame.to_json — pandas documentation
Will throw ValueError if incorrect ‘orient’ since others are not list-like. ... For on-the-fly compression of the output data. If ‘infer’ and ‘path_or_buf’ is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, ‘.xz’, ‘.zst’, ‘.tar’, ‘.tar.gz’, ‘.tar.xz’ or ‘.tar.bz2’ (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of {'zip', 'gzip', 'bz2', 'zstd', 'xz', 'tar'} and other key-value pairs are forwarded to zipfile.ZipFile, gzip.GzipFile, bz2.BZ2File, zstandard.ZstdCompressor, lzma.LZMAFile or tarfile.TarFile, respectively.
Top answer
1 of 2
2

Pandas is equipped for this out of the box.

pandas.DataFrame.to_json

here is the example dataframe:

import json
df = pd.DataFrame(
    [["a", "b"], ["c", "d"]],
    index=["row 1", "row 2"],
    columns=["col 1", "col 2"],
)

Here is the result using to_json():

result = df.to_json(orient="split")
parsed = json.loads(result)
json.dumps(parsed, indent=4)  
{
    "columns": [
        "col 1",
        "col 2"
    ],
    "index": [
        "row 1",
        "row 2"
    ],
    "data": [
        [
            "a",
            "b"
        ],
        [
            "c",
            "d"
        ]
    ]
}

here is the link: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html

2 of 2
1

As per the function provided here @Parsa T. You can just change the column names and use the function to get the required result.

def set_for_keys(my_dict, key_arr, val):
    """
    Set value at the path in my_dict defined by the string (or serializable object) array key_arr
    """
    current = my_dict
    for i in range(len(key_arr)):
        key = key_arr[i]
        if key not in current:
            current[key] = val if i==len(key_arr)-1 else {}
        else:
            if type(current[key]) is not dict:
                print("Given dictionary is not compatible with key structure requested")
                raise ValueError("Dictionary key already occupied")

        current = current[key]

    return my_dict

def to_formatted_json(df, sep="."):
    result = []
    for _, row in df.iterrows():
        parsed_row = {}
        for idx, val in row.iteritems():
            keys = idx.split(sep)
            parsed_row = set_for_keys(parsed_row, keys, val)

        result.append(parsed_row)
    return result


df.columns = ['ID', 'PERSONAL.NAME', 'PERSONAL.LAST', 'GEO.ADDRESS', 'GEO.COUNTY']
#Where df was parsed from json-dict using json_normalize
print(to_formatted_json(df, sep="."))

OUTPUT:

[{'ID': '0',
  'PERSONAL': {'NAME': 'jimmy', 'LAST': 'neutron'},
  'GEO': {'ADDRESS': '101 ocean avenue', 'COUNTY': 'yellow card park'}},
 {'ID': '1',
  'PERSONAL': {'NAME': 'james', 'LAST': 'baxter'},
  'GEO': {'ADDRESS': '202 bubble gum county', 'COUNTY': 'candy kingdom'}},
 {'ID': '2',
  'PERSONAL': {'NAME': 'joben', 'LAST': 'segel'},
  'GEO': {'ADDRESS': '303 china town', 'COUNTY': 'universal studio'}}]
🌐
Pandas
pandas.pydata.org › docs › reference › api › pandas.read_json.html
pandas.read_json — pandas 3.0.2 documentation - PyData |
The encoding to use to decode py3 bytes. encoding_errorsstr, optional, default “strict” · How encoding errors are treated. List of possible values . ... Read the file as a json object per line.
🌐
Stack Overflow
stackoverflow.com › questions › 73807703 › how-to-place-json-key-values-into-columns-using-pandas-dataframe
python - How to place JSON key values into columns using Pandas Dataframe - Stack Overflow
you can store the key/value pairs as json strings in a column. you then can use the key/value pair later by access the contents of the column and loading the data into a dictionary · ListenSoftware Louise Ai Agent – ListenSoftware Louise ...
🌐
Reddit
reddit.com › r/learnpython › using values of dataframe column as json keys
r/learnpython on Reddit: Using values of dataframe column as JSON Keys
January 18, 2024 - I have a pandas dataframe with 6 columns that I am trying to convert to JSON in a desired format. What I've been having trouble with is using the…
🌐
Data to Fish
datatofish.com › export-pandas-dataframe-json
How to Export a pandas DataFrame as a JSON File
import pandas as pd data = {'fish': ['salmon', 'pufferfish', 'shark'], 'count': [100, 10, 1], } df = pd.DataFrame(data) print(df) ... import os desktop_path = os.path.expanduser('~/Desktop') df.to_json(desktop_path + '/fish.json', orient='columns')
🌐
w3resource
w3resource.com › pandas › dataframe › dataframe-to_json.php
Pandas DataFrame: to_json() function - w3resource
August 19, 2022 - Returns: None or str If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None. ... Download the Pandas DataFrame Notebooks from here.
🌐
Pandas
pandas.pydata.org › pandas-docs › version › 1.2.3 › reference › api › pandas.DataFrame.to_json.html
pandas.DataFrame.to_json — pandas 1.2.3 documentation
Extra options that make sense for ... docs for the set of allowed keys and values. New in version 1.2.0. ... If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None. ... Convert a JSON string to pandas object....