csv到python中的json

时间:2016-01-13 15:13:01

标签: python json csv

嘿所以我在csv文件中有一些哈希id,比如

XbRPhe65YbC + xtgGQ8ukeZEr9xFOC4MEs9Z0wUidGSec = XbRPhe65YbC + xtgGQ8uksrqSUJ / HhTPj1d2pL0 / vuGrHM =

我希望将它们解析为python,将它们包含在一些额外的代码中,如

{" ID" :" XbRPshe65YbC + xtGQ8ukqR2u2btfNeNegtgtcs72QbxPA ="," timestamp":" 20150831"},

然后用一些JSON语法包装所有这些。然后将其作为发布请求发送。问题是我似乎无法使JSON可读。一切似乎都是错误的,我得到额外的\。

import os
import pandas as pd
from pprint import pprint

df=pd.read_csv('test.csv',sep=',',header=None)
df[0] = '{"id" :"' + df[0].astype(str) + '", "timestamp":"20150831"}, ' 

df = df[:-1] # removes last comma


test = 'hello'
data =[ { "ids":[ df[0]],
          "attributes":[
                {
                "name":"girl"
                },
                {
                "name":"size"
                }
                ]
        }
        ]

json1 = data.to_json()
print(json1)

1 个答案:

答案 0 :(得分:2)

我同意大熊猫似乎不是这里工作的最简单的工具。内置库可以很好地工作:

import csv
import json

with open('test.csv', newline='') as csvfile:
    csvreader = csv.reader(csvfile)

    data = {
        "ids": [{"id": row[0], "timestamp": "20150831"} for row in csvreader],
        "attributes": [
            {"name": "girl"},
            {"name": "size"}
        ]
    }

json1 = json.dumps(data)
print(json1)