user8306074
user8306074

Reputation: 395

Convert excel to json python

I have an excel sheet with two columns and I want to convert it into json. enter image description here

I want to convert this into a json format like this:

{"A": "This is a Sentence", "B": "1"},
{"A": "This is a Sentence", "B": "2"},
{"A": "This is a Sentence", "B": "3"},
{"A": "This is a Sentence", "B": "4"}

I tried using this command:

data= df.to_json (r'C:\Users\Admin\df_json.json',orient='split')

but it generates something like this:

[{"A": "This is a Sentence", "B": "1"},{"A": "This is a Sentence", "B": "2"},{"A": "This is a Sentence", "B": "3"},{"A": "This is a Sentence", "B": "4"},]

Upvotes: 0

Views: 362

Answers (1)

Felk
Felk

Reputation: 8224

The result you are getting is normal json. What you described as your desired result is json lines (also called jsonlines, jsonl or similar). There's no built-in support for it as far as I know, but if you want to output json lines it's pretty easy to do by hand. Here's an example on how you would write json lines to a file:

data = df.to_json (r'C:\Users\Admin\df_json.json', orient='split')
with open("converted.jsonl", mode="wt", encoding="utf-8") as f:
    for line in data:
        f.write(json.dumps(line) + "\n")

Upvotes: 2

Related Questions