satya veni
satya veni

Reputation: 17

How to add square brackets in JSON object with python

I just need contexts to be an Array ie., 'contexts' :[{}] instead of 'contexts':{}

Below is my python code which helps in converting python data-frame to required JSON format

This is the sample df for one row

name      type  aim      context     
xxx xxx     specs 67646546  United States of America  

data = {'entities':[]}
for key,grp in df.groupby('name'):
    for idx, row in grp.iterrows():
        temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}}

        attr_row = row[~row.index.isin(['name','type'])]
        for idx2,row2 in attr_row.iteritems():
            dict_temp = {}
            dict_temp[idx2] = {'values':[]}
            dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'})

            temp_dict_alpha['data']['contexts']['attributes'].update(dict_temp)


        data['entities'].append(temp_dict_alpha)


print(json.dumps(data, indent = 4))

Desired output:

{
    "entities": [{
            "name": "XXX XXX",
            "type": "specs",
            "data": {
                "contexts": [{
                        "attributes": {
                            "aim": {
                                "values": [{
                                        "value": 67646546,
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            }
                        },
                        "context": {
                            "country": "United States of America"
                        }
                    }
                ]
            }
        }
    ]
}

However I am getting below output

{
    "entities": [{
            "name": "XXX XXX",
            "type": "specs",
            "data": {
                "contexts": {
                    "attributes": {
                        "aim": {
                            "values": [{
                                    "value": 67646546,
                                    "source": "internal",
                                    "locale": "en_Us"
                                }
                            ]
                        }
                    },
                    "context": {
                        "country": "United States of America"
                    }
                }
            }
        }
    ]
}

Can any one please suggest ways for solving this problem using Python.

Upvotes: 0

Views: 1718

Answers (2)

chitown88
chitown88

Reputation: 28595

I think this does it:

import pandas as pd
import json


df = pd.DataFrame([['xxx xxx','specs','67646546','United States of America']],
                       columns = ['name', 'type', 'aim', 'context' ])

data = {'entities':[]}
for key,grp in df.groupby('name'):
    for idx, row in grp.iterrows():
        temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':[{'attributes':{},'context':{'country':row['context']}}]}}

        attr_row = row[~row.index.isin(['name','type'])]
        for idx2,row2 in attr_row.iteritems():
            if idx2 != 'aim':
                continue
            dict_temp = {}
            dict_temp[idx2] = {'values':[]}
            dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'})

            temp_dict_alpha['data']['contexts'][0]['attributes'].update(dict_temp)


        data['entities'].append(temp_dict_alpha)


print(json.dumps(data, indent = 4))

Output:

{
    "entities": [
        {
            "name": "xxx xxx",
            "type": "specs",
            "data": {
                "contexts": [
                    {
                        "attributes": {
                            "aim": {
                                "values": [
                                    {
                                        "value": "67646546",
                                        "source": "internal",
                                        "locale": "en_Us"
                                    }
                                ]
                            }
                        },
                        "context": {
                            "country": "United States of America"
                        }
                    }
                ]
            }
        }
    ]
}

Upvotes: 1

Gagan
Gagan

Reputation: 5656

The problem is here in the following code

 temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}}

As you can see , you are already creating a contexts dict and assigning values to it. What you could do is something like this

    contextObj = {'attributes':{},'context':{'dcountry':row['dcountry']}}
    contextList = []
    for idx, row in grp.iterrows():
        temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}}

        attr_row = row[~row.index.isin(['name','type'])]
        for idx2,row2 in attr_row.iteritems():
            dict_temp = {}
            dict_temp[idx2] = {'values':[]}
            dict_temp[idx2]['values'].append({'value':row2,'source':'internal','locale':'en_Us'})
            contextObj['attributes'].update(dict_temp)
            contextList.append(contextObj)

Please Note - This code will have logical errors and might not run ( as it is difficult for me , to understand the logic behind it). But here is what you need to do .

You need to create a list of objects, which is not what you are doing. You are trying to manipulate an object and when its JSON dumped , you are getting an object back instead of a list. What you need is a list. You create context object for each and every iteration and keep on appending them to the local list contextList that we created earlier.

Once when the for loop terminates, you can update your original object by using the contextList and you will have a list of objects instead of and object which you are having now.

Upvotes: 0

Related Questions