Python :: pandas和json.dumps

时间:2018-03-18 05:23:33

标签: python json pandas

我正在使用pandas从excel和json中读取以创建一个json。

for x in range(1,n)
    label = (df.columns[x]).strip()
    something = (df[df.columns[x]][i])
    print (label)
    print (something)

这给了我正好在我正在读的excel中所拥有的......

productTypes
"APPLE","BANANA"

当我做一个json.dumps ......

for x in range(1,n)
    label = (df.columns[x]).strip()
    something = (df[df.columns[x]][i])
    value = json.dumps(something)
    print (label)
    print (value)

这给了我

productTypes
"\"APPLE\",\"BANANA\""

我在json中需要的是......

"productTypes":["APPLE","BANANA"]

帮助?

1 个答案:

答案 0 :(得分:0)

dictlabel中创建something,然后执行json.dumps()

简单示例 -

import json

label = 'productTypes'
something = ["APPLE","BANANA"]
print(json.dumps({label: something}))

<强>输出

{"productTypes": ["APPLE", "BANANA"]}

因此,在您的情况下,为dictlabel声明something。像 -

这样的东西
for x in range(1,n)
    label = (df.columns[x]).strip()
    something = (df[df.columns[x]][i])
    print (label)
    print (something)
    value = json.dumps({label: something})