0

Is it possible to write json to file without index values and nesting using any Python library function e.g. pandas.DataFrame.to_json? My dataframe is only ever going to have one row, and the system that parses it cannot handle index values and requires the structure to be in this specific way.

What I want to achieve:

{"A":"D","B":"F","C":"G"}

Code example:

import pandas as pd
data = [["D", "F", "G"]]

df = pd.DataFrame(data, columns = ["A", "B", "C"])
result = df.to_json(orient="columns")

with open("test.txt", "w") as f:
    f.write(result)

Tried so far:

df.to_json(orient="columns")
# {"A":{"0":"D"},"B":{"0":"F"},"C":{"0":"G"}}

df.to_json(orient="records")
# [{"A":"D","B":"F","C":"G"}]

df.to_json(orient="split")
# {"columns":["A","B","C"],"index":[0],"data":[["D","F","G"]]}

While what I want looks suspiciously like Python dictionary, I still want to know how to write to the file, and writing a dictionary {"A":"D","B":"F","C":"G"} to file throws

TypeError: write() argument must be str, not dict
2
  • 1
    call str() on it, or use .to_json() instead of .to_dict() Commented Aug 26, 2021 at 20:33
  • Does this answer your question? TypeError: the JSON object must be str, not 'dict' Commented Aug 26, 2021 at 20:34

1 Answer 1

2

IIUC, since you only have one row:

>>> df.iloc[0].to_json()
'{"A":"D","B":"F","C":"G"}'

To write to file:

with open("test.txt", "w") as f:
    f.write(df.iloc[0].to_json())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.