我在数据框df中有一个json列,在这里我试图将其转换为嵌套的json并将其另存为客户端的txt文件:
数据帧df
"json":{"0":{"status":"Active","task_name":"transientAlertf9b8b69eb4b84bd597b3983566ffc538","schedule":"","owner":"","task_type":"FraudIncremental","created_date":"Tue, 08 Jan 2019 00:34:43 GMT","parameters":{"program":"abc","subject":"abc ","days_back":1,"last_run_status":"OK"},"category":"Alert","permission":"private","messaging_channels":[{"channel_type":"email","cc":"","recipients":[""],"bcc":""}],"tags":"Fraud"}}}
放入嵌套的json并保存为txt
{
"created_date": "Tue, 08 Jan 2019 00:34:43 GMT",
"schedule": "",
"parameters": {
"last_run_status": "OK",
"subject": "abc ",
"days_back": 1,
"program": "abc"
},
"status": "Active",
"permission": "private",
"task_type": "abc",
"tags": "Fraud",
"messaging_channels": [
{
"bcc": "",
"cc": "",
"channel_type": "email",
"recipients": [
""
]
}
],
"task_name": "transientAlertf9b8b69eb4b84bd597b3983566ffc538",
"category": "Alert",
"owner": ""
}
有什么想法吗?谢谢。
我检查了一些帖子,它们并不完全相同
Pandas DataFrame to Nested JSON Without Changing Data Structure
答案 0 :(得分:1)
从您作为示例给出的df开始:
df = pd.DataFrame({"json":{"0":{"status":"Active","task_name":"transientAlertf9b8b69eb4b84bd597b3983566ffc538","schedule":"","owner":"","task_type":"FraudIncremental","created_date":"Tue, 08 Jan 2019 00:34:43 GMT","parameters":{"program":"abc","subject":"abc ","days_back":1,"last_run_status":"OK"},"category":"Alert","permission":"private","messaging_channels":[{"channel_type":"email","cc":"","recipients":[""],"bcc":""}],"tags":"Fraud"}}})
df
json
0 {'status': 'Active', 'task_name': 'transientAl...
运行以下代码,将json
列中所有行的内容转换为json条目,并将它们全部保存到文本文件中,这些文件的格式看起来不错:
import json
json_data = df['json'].to_json(orient='index')
with open('data.txt', 'w') as outfile:
json.dump(json.loads(json_data), outfile, sort_keys=True, indent=2)
在记事本中打开时,data.txt
的显示方式如下:
{
"0": {
"category": "Alert",
"created_date": "Tue, 08 Jan 2019 00:34:43 GMT",
"messaging_channels": [
{
"bcc": "",
"cc": "",
"channel_type": "email",
"recipients": [
""
]
}
],
"owner": "",
"parameters": {
"days_back": 1,
"last_run_status": "OK",
"program": "abc",
"subject": "abc "
},
"permission": "private",
"schedule": "",
"status": "Active",
"tags": "Fraud",
"task_name": "transientAlertf9b8b69eb4b84bd597b3983566ffc538",
"task_type": "FraudIncremental"
}
}