How to add square brackets in JSON object with python

血红的双手。 提交于 2019-12-23 04:56:41

问题


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.


回答1:


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"
                        }
                    }
                ]
            }
        }
    ]
}



回答2:


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.



来源:https://stackoverflow.com/questions/57660887/how-to-add-square-brackets-in-json-object-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!