2

I have as an output from my Python script a JSon format and I want to write the JSon into a file.

I use

df_json.to_json(orient='records') 

with open('JSONData.json', 'w') as f:
     json.dump(df_json, f)

I have the following error:

raise TypeError(repr(o) + " is not JSON serializable")

[1746 rows x 2 columns] is not JSON serializable

I don't know what I am doing wrong.

My JSon output is as follows :

[
  {
    "id": 1,
    "results": [
      1,
      2,
      3

    ]
  },
  {
    "id": 558599,
    "results": [
      4,
      5,
      6
    ]
  }
]

Thank you in advance.

1 Answer 1

2

you're calling df_json.to_json(orient='records') but you don't use the results. Object is not going to mutate itself into a jsonisable object.

Serializing the original object obviously doesn't work (or there wouldn't be a to_json method on it)

Since the string is already json, you don't even need the json module (or json would try to serialize the string again, which is not what you want): just do:

f.write(df_json.to_json(orient='records'))
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer, I have used this but I get some strange output with a slash ( \ ) before every double quotes ( " )
The output in my file is "[ { \"id\": 1, \"results\": [ 1, 2, 3 ] } ] "
sorry, I was mistaken earlier. It's simpler than that. Edited my answer...
Thank you, that's what I was searching for ;)

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.