我有一个包含 4 列数据的 csv 文件,如下所示。
type,MetalType,Date,Acknowledge
Metal,abc123451,2018-05-26,Success
Metal,abc123452,2018-05-27,Success
Metal,abc123454,2018-05-28,Failure
Iron,abc123455,2018-05-29,Success
Iron,abc123456,2018-05-30,Failure
(我只是在上面的示例数据中提供了标题,但在我的情况下,数据中没有标题)
如何将上面的 csv 文件转换为以下格式的 Json...
第一列:属于 --> "type": "Metal"
第二列:MetalType:“值”:“值”:“abc123451”
第三列:“日期”:“值”:“值”:“2018-05-26”
第四列:“Acknowledge”:“values”:“value”:“成功”
其余所有列均为默认值。
按照以下格式,
{
"entities": [
{
"id": "XXXXXXX",
"type": "Metal",
"data": {
"attributes": {
"MetalType": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": "abc123451"
}
]
},
"Date": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": "2018-05-26"
}
]
},
"Acknowledge": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": "Success"
}
]
}
}
}
}
]
}
最佳答案
尽管 jww 是对的,但我还是为你构建了一些东西:
我使用 pandas 导入 csv:
df = pd.read_csv('data.csv')
然后我为您要添加的词典创建一个模板:
d_json = {"entities": []}
template = {
"id": "XXXXXXX",
"type": "",
"data": {
"attributes": {
"MetalType": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": ""
}
]
},
"Date": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": ""
}
]
},
"Acknowledge": {
"values": [
{
"source": "XYZ",
"locale": "Australia",
"value": ""
}
]
}
}
}
}
现在您只需填写字典即可:
for i in range(len(df)):
d = template
d['type'] = df['type'][i]
d['data']['attributes']['MetalType']['values'][0]['value'] = df['MetalType'][i]
d['data']['attributes']['Date']['values'][0]['value'] = df['Date'][i]
d['data']['attributes']['Acknowledge']['values'][0]['value'] = df['Acknowledge'][i]
d_json['entities'].append(d)
我知道我迭代 df 的方式有点难看,也许有人知道一种更干净的方式。
干杯!
关于python - 如何将多值 CSV 转换为 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56648517/