如何使用python在JSON对象中添加方括号
我只需要上下文是一个数组,即,'contexts':[{}],而不是'contexts':{} 下面是我的python代码,它有助于将python数据帧转换为所需的JSON格式 这是一行的示例df如何使用python在JSON对象中添加方括号,python,arrays,json,python-3.x,nested,Python,Arrays,Json,Python 3.x,Nested,我只需要上下文是一个数组,即,'contexts':[{}],而不是'contexts':{} 下面是我的python代码,它有助于将python数据帧转换为所需的JSON格式 这是一行的示例df name type aim context xxx xxx specs 67646546 United States of America data = {'entities':[]} for key,grp in df.groupby('name'):
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))
期望输出:
{
"entities": [{
"name": "XXX XXX",
"type": "specs",
"data": {
"contexts": [{
"attributes": {
"aim": {
"values": [{
"value": 67646546,
"source": "internal",
"locale": "en_Us"
}
]
}
},
"context": {
"country": "United States of America"
}
}
]
}
}
]
}
然而,我得到以下输出
{
"entities": [{
"name": "XXX XXX",
"type": "specs",
"data": {
"contexts": {
"attributes": {
"aim": {
"values": [{
"value": 67646546,
"source": "internal",
"locale": "en_Us"
}
]
}
},
"context": {
"country": "United States of America"
}
}
}
}
]
}
任何人都可以提出使用Python解决此问题的方法。问题在下面的代码中
temp_dict_alpha = {'name':key,'type':row['type'],'data' :{'contexts':{'attributes':{},'context':{'dcountry':row['dcountry']}}}}
如您所见,您已经在创建一个上下文
dict
并为其赋值。你能做的就是这样
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)
请注意-此代码将有逻辑错误,可能无法运行(因为我很难理解其背后的逻辑)。但这是你需要做的
您需要创建一个对象列表,这不是您正在做的事情。您试图操纵一个对象,当它的JSON被转储时,您得到的是一个对象,而不是一个列表。你需要的是一份清单。您为每个迭代创建上下文对象,并继续将它们附加到我们先前创建的本地列表contextList
for循环终止后,您可以使用contextList
更新原始对象,您将拥有一个对象列表,而不是您现在拥有的和object
。我认为这样做:
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))
输出:
{
"entities": [
{
"name": "xxx xxx",
"type": "specs",
"data": {
"contexts": [
{
"attributes": {
"aim": {
"values": [
{
"value": "67646546",
"source": "internal",
"locale": "en_Us"
}
]
}
},
"context": {
"country": "United States of America"
}
}
]
}
}
]
}
谢谢你的回复。不符合你的逻辑。我得到了同样的旧输出。非常感谢@chitown。然而,在上面的逻辑中,我们需要嵌套的对象“attributes”是数组而不是对象。[{“entities”:[{“name”:“specs”,“type”:“glass”,“data”:{“attributes”:[{“aitm”:{“values”:[{“value”:“70072187”,“source”:“internal”,“locale”:“en_US”}}],“alitm”:{“values”:[{“value”:[{“value”:“ESA65Z45”,“source internal”,“locale”:“en_US”}]}],“aaitm”:{“values”:“value”:“ESA 65Z45”,“来源”:“内部”,“地区”:“en_US”}]},“adsc1”:{“值”:[{“值”:“切割提示FG 1808-40”,“来源”:“内部”,“地区”:“en_US”}]}]}]}]}]啊。好吧,我误读了。我明白你的意思。有机会我会解决这个问题的。我再次需要你的帮助。我正在尝试以下面的格式向数据添加一个对象。你能帮我一下吗。{”实体“:[{”名称“:”xxx xxx”,“类型“:”规范“,”数据“:{”属性“:{”aimd“:{”值“:”xxxxx“,”来源“:”内部“,”地区“:”en_Us“}}}}”,上下文“:[{”属性“:{”目标“{”值“:[{”值“:”67646546”,“源“:”内部“,”地区“:”en_Us“}}}”,上下文“{”国家“:”美利坚合众国“}}”您的数据源不完整。aimd在您的数据源中的何处可以获取该值?请共享数据源的整行,以便我可以计算出逻辑。抱歉。下面是示例数据源。df=pd.DataFrame([['xxx xxx','specs','67646546','TEST 123','United of America']],columns=['name'、'type'、'aim'、'aimd'、'context'])