Remove index from dataframe before converting to split orientation json

I have outputted the pandas framework to a json object using the following:

df_as_json = df.to_json(orient='split')

      

The json object stores extra indices. I don't want to include them.

To remove them I tried

df_no_index = df.to_json(orient='records')
df_as_json = df_no_index.to_json(orient='split')

      

However I am getting

AttributeError: 'str' object has no attribute 'to_json'

      

Is there a quick way to reorganize the DataFrame so that it doesn't contain a separate index column during or before calling .to_json (orient = 'split')?

+3


source to share


1 answer


  • Convert to json

    usingto_json(orient='split')

  • Use a module json

    to load this string into a dictionary
  • Remove the key index

    withdel json_dict['index']

  • Convert the dictionary back to json

    using json.dump

    orjson.dumps




Demo

df = pd.DataFrame([[1, 2], [3, 4]], ['x', 'y'], ['a', 'b'])

json_dict = json.loads(df.to_json(orient='split'))
del json_dict['index']
json.dumps(json_dict)

'{"columns": ["a", "b"], "data": [[1, 2], [3, 4]]}'

      

+2


source







All Articles