0

I have json like this:

json = {
 "b": 22,
 "x": 12,
 "a": 2,
 "c": 4
}

When i generate an Excel file from this json like this:

import pandas as pd

df = pd.read_json(json_text)
file_name = 'test.xls'
file_path = "/tmp/" + file_name
df.to_excel(file_path, index=False)

print("path to excel " + file_path)

Pandas does its own ordering in the Excel file like this:

pandas_json = {
"a": 2,
"b": 22,
"c": 4,
"x": 12
}

I don't want this. I need the ordering which exists in the json. Please give me some advice how to do this.

UPDATE: if i have json like this:

json = [
{"b": 22, "x":12, "a": 2, "c": 4},
{"b": 22, "x":12, "a": 2, "c": 2},
{"b": 22, "x":12, "a": 4, "c": 4},
]

pandas will generate its own ordering like this:

panas_json = [
{"a": 2, "b":22, "c": 4, "x": 12},
{"a": 2, "b":22, "c": 2, "x": 12},
{"a": 4, "b":22, "c": 4, "x": 12},
]

How can I make pandas preserve my own ordering?

1 Answer 1

1

You can read the json as OrderedDict which will help to retain original order:

import json
from collections import OrderedDict

json_ = """{
"b": 22,
"x": 12,
"a": 2,
"c": 4
}"""

data = json.loads(json_, object_pairs_hook=OrderedDict)
pd.DataFrame.from_dict(data,orient='index')

    0
b  22
x  12
a   2
c   4

Edit, updated json also works:

j="""[{"b": 22, "x":12, "a": 2, "c": 4},
{"b": 22, "x":12, "a": 2, "c": 2},{"b": 22, "x":12, "a": 4, "c": 4}]"""

data = json.loads(j, object_pairs_hook=OrderedDict)
pd.DataFrame.from_dict(data).to_json(orient='records')

'[{"b":22,"x":12,"a":2,"c":4},{"b":22,"x":12,"a":2,"c":2}, 
  {"b":22,"x":12,"a":4,"c":4}]'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! can you look at the more complex jason? I have updated my question

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.