如何创建数据框以生成给定格式的 json

how to create a dataframe to generate json in the given format

我需要从我的数据帧生成一个 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'}]"}}  

我认为你需要:


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'))