1

I currently have a Python Pandas DataFrame that I would like to convert to a custom JSON structure. Does anyone know how I can achieve this? I'd love to hear it, thanks in advance!

Current Pandas DataFrame structure:

ArticleNumber | Brand | Stock | GroupCode
-----------------------------------
1  |    Adidas     | 124      | 20.0

I would like to transform the above dataframe into a JSON structure below:

{
  "Attributes": [
    {
      "Key": “ArticleNumber”,
      "Values": [
        “1”
      ]
    },
    {
      "Key": “Brand”,
      "Values": [
        “Adidas”
      ]
    },
    {
      "Key": “Stock”,
      "Values": [
        “124”
      ]
    },
    {
      "Key": “GroupCode”,
      "Values": [
        “20.0”
      ]
    },
  ]
}
4
  • What is ouput if 2 or more rows in DataFrame? Commented Jun 27, 2022 at 7:53
  • 1
    Good question! My bad, should have been more clear. I want to create a new column in the Pandas DataFrame with name: 'JSON Structure'. I want to transform each instance and save the transformation for in the column 'JSON Structure'. Is that more clear? @jezrael Commented Jun 27, 2022 at 8:03
  • Can you test now? Commented Jun 27, 2022 at 8:09
  • 1
    Your a legend. Thanks! @jezrael Commented Jun 27, 2022 at 9:53

1 Answer 1

1

Use list with dict comprehension for custom format:

import json

L = df.to_dict('records')


df['DICT'] = [{"Attributes":[{'Key':k,'Values':[v]} 
               for k, v in x.items()]} for x in L]

df['JSON'] = [json.dumps({"Attributes":[{'Key':k,'Values':[v]} 
                for k, v in x.items()]}) for x in L]
print (df)
   ArticleNumber    Brand  Stock  GroupCode  \
0              1   Adidas    124      20.00   
1              2  Adidas1   1241      20.01   

                                                DICT  \
0  {'Attributes': [{'Key': 'ArticleNumber', 'Valu...   
1  {'Attributes': [{'Key': 'ArticleNumber', 'Valu...   

                                                JSON  
0  {"Attributes": [{"Key": "ArticleNumber", "Valu...  
1  {"Attributes": [{"Key": "ArticleNumber", "Valu...  
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.