如何创建一个数据帧以生成给定格式的json

时间:2017-10-30 09:50:55

标签: python json pandas dataframe to-json

我需要从我的数据帧生成一个json,但是我尝试了很多df格式但是我仍然无法获得所需的json格式。

我需要的json格式是,

[
    {
        "Keyword": "Red", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }, 
     {
        "Keyword": "Orange", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }, 
     {
        "Keyword": "Violet", 
        "values": [
            {
                "value": 5, 
                "TC": "Color"
            }            
        ]
    }
]

我想要一个df来生成这个json。请帮忙。

但目前我正在获取df.to_json:

 {"Names":{"0":"Ram","1":"pechi","2":"Sunil","3":" Ravi","4":"sri"},"Values":{"0":"[{'value':2,'TC': 'TC Count'}]","1":"[{'value':2,'TC': 'TC Count'}]","2":"[{'value':1,'TC': 'TC Count'}]","3":"[{'value':1,'TC': 'TC Count'}]","4":"[{'value':1,'TC': 'TC Count'}]"}}  

1 个答案:

答案 0 :(得分:1)

我认为你需要:

print (df)

  Keyword     TC  value
0     Red  Color      5
1  Orange  Color      5
2  Violet  Color      5
j = (df.set_index('Keyword')
        .apply(lambda x: [x.to_dict()], axis=1)
        .reset_index(name='values')
        .to_json(orient='records'))
print (j)

[{"Keyword":"Red","values":[{"TC":"Color","value":5}]},
 {"Keyword":"Orange","values":[{"TC":"Color","value":5}]},
 {"Keyword":"Violet","values":[{"TC":"Color","value":5}]}]

写入file

(df.set_index('Keyword')
   .apply(lambda x: [x.to_dict()], axis=1)
   .reset_index(name='values')
   .to_json('myfile.json', orient='records'))