1

from a Dataframe, I want to have a JSON output file with one key having a list:

Expected output:

[
  {
    "model": "xx",
    "id": 1,
    "name": "xyz",
    "categories": [1,2],
  },
  {
    ...
  },
]

What I have:

[
  {
    "model": "xx",
    "id": 1,
    "name": "xyz",
    "categories": "1,2",
  },
  {
    ...
  },
]

The actual code is :

df = pd.read_excel('data_threated.xlsx')
result = df.reset_index(drop=True).to_json("output_json.json", orient='records')
parsed = json.dumps(result)

jsonfile = open("output_json.json", 'r')
data = json.load(jsonfile)

How can I achive this easily?

EDIT:

print(df['categories'].unique().tolist())

['1,2,3', 1, nan, '1,2,3,6', 9, 8, 11, 4, 5, 2, '1,2,3,4,5,6,7,8,9']
1
  • Will you please show a sample of your dataframe? :) Commented Feb 4, 2022 at 15:11

1 Answer 1

1

You can use:

df = pd.read_excel('data_threated.xlsx').reset_index(drop=True)
df['categories'] = df['categories'].apply(lambda x: [int(i) for i in x.split(',')] if isinstance(x, str) else '')
df.to_json('output.json', orient='records', indent=4)

Content of output.json

[
    {
        "model":"xx",
        "id":1,
        "name":"xyz",
        "categories":[
            1,
            2
        ]
    }
]

Note you can also use:

df['categories'] = pd.eval(df['categories'])
Sign up to request clarification or add additional context in comments.

11 Comments

I have an error AttributeError: 'int' object has no attribute 'split' Maybe it's due to the inconsistent data in catagories: I may have - "1,2,3" - "1" (this one is treated like an integer) - "" (empty)
Ok. I will fixed it
Ok you have more 100 records in your dataframe so pd.eval is useless here
Can you update your post with the output of df['categories'].unique().tolist() please?
Still not working, really struggling here :/ df['categories'] = df['categories'].apply(lambda x: [int(i) for i in x.split(',')] if isinstance(str, x) else '') TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
|

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.