0

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

1 回答 1

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'))
于 2017-10-30T11:10:17.687 回答