Flask Restful:将CSV文件转换为JSON对象

时间:2018-10-09 21:19:09

标签: python pandas csv flask flask-restful

我正在从前端读取文件并将其转换为JSON,其中包含uuid和JSON对象列表:

class File(Resource):

def post(self):
    if 'file' not in request.files:
        return {"message": "No File in the request!"}, 400
    file = request.files['file']

    if file.filename == '':
        return {'message': "No File selected!"}, 400

    if file:
        filename = secure_filename(file.filename)

    #file_contents = file.read()
    print(file)
    converted_json = File.csv2json(file)
    new_request = {
            'uuid': str(uuid.uuid4()),
            'devices': converted_json
        }
    print(new_request)
    return new_request, 201

@classmethod
def csv_to_json(cls, data):
    df = pd.read_csv(data, header=None)
    df.columns = ['name', 'username', 'password', 'domain']
    print(df)
    df = df.to_json(orient='records')
    print(df)
    return df

输出是双重编码的: {     “ uuid”:“ 1a09ad79-dc78-4759-9aa0-f1dda9c08dc4”,     “ details”:“ [{\” name \“:\” joe \“,\” username \“:\” admin \“,\” password \“:\” admin \“,\” domain \“:\ “ abc.xyz.com \”}]“ }

如何获取JSON对象输出(在每个','的末尾加上换行符):

{
"uuid": "1a09ad79-dc78-4759-9aa0-f1dda9c08dc4",
"details": [
               {"name": "joe",
                "username": "admin",
                "password": "admin",
                "domain"" "abc.xyz.com"}
           ]
}

1 个答案:

答案 0 :(得分:0)

没关系!

在'df = df.to_json(orient ='records')'之后使用'json.loads(df)'可以达到目的!