Python 3.x 如何使用DataFrame将csv文件转换为嵌套json格式

Python 3.x 如何使用DataFrame将csv文件转换为嵌套json格式,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,我正在使用熊猫库读取.csv文件,并使用json库将csv文件转换为json,但在我的csv文件中,有一列包含一个列表,我还必须将其转换为json数组列表,但它正在转换为字符串格式 这是我的csv内容 recipe_id | recipe_name | ingredients2 | 240488 Pork Loin [{"title":"basmati rice","quantity":"1 cup&q

我正在使用熊猫库读取
.csv
文件,并使用
json
库将
csv
文件转换为
json
,但在我的
csv
文件中,有一列包含一个列表,我还必须将其转换为
json数组列表
,但它正在转换为
字符串格式

这是我的csv内容

recipe_id | recipe_name | ingredients2 |
 
   240488    Pork Loin     [{"title":"basmati rice","quantity":"1 cup"}, 
                           {"title":"mint  leaves","quantity":"1/2teaspoon"}, 
                           {"title":"salt","quantity":"as required"}]
   
   218939     Foolproof       [{"title":"Meat","quantity":"1 kg"}, 
              Rosemary             {"title":"Water","quantity":"1 Glass"}, 
                           {"title":"Mirch powder","quantity":"5 -10 Teaspoon"}]
             
这是我的密码

import numpy as np
import pandas as pd
import json
from flask import Flask, render_template

app = Flask(__name__)

df = pd.read_csv('sample.csv')


  @app.route("/index")
  def index():


     data = pd.DataFrame(df[['recipe_id', 'recipe_name', 'ingredients2']])

     return_data = data.to_json(orient="records")
     prse = json.loads(return_data)

    response = app.response_class(
    response=json.dumps(prse, indent=4),
    status=200,
    mimetype='application/json'
   )

   return response



if __name__ == '__main__':
     app.run(debug=True)
输出:

[
  {
     recipe_id: 240488,
     recipe_name: "Pork Loin, Apples, and Sauerkraut",
     ingredients2: "[{"title":"basmati rice","quantity":"1 cup"},{"title":"mint 
                     leaves","quantity":"1/2 teaspoon"},{"title":"salt","quantity":"as required"}]"
   },
   {
       recipe_id: 218939,
       recipe_name: "Foolproof Rosemary Chicken Wings",
       ingredients2: "[{"title":"Meat","quantity":"1 kg"},{"title":"Water","quantity":"1 Glass"}, 
                      {"title":"Mirch powder","quantity":"5 -10 Teaspoon"}]"
    }, 
 ]
预期产出:

[
   {
      title: "Biryani",
      description: "Chicken Biryani",
      ingredients2: [
                       {
                          title: "basmati rice",
                          quantity: "1 cup"
                        },
                        {
                           title: "mint leaves",
                           quantity: "1/2 teaspoon"
                        },
                        {
                            title: "salt",
                            quantity: "as required"
                        }
                 ]
     }
]
请帮我做这个

  • 您提供的示例数据看起来不正确。它不是CSV,它是管道和空间分隔的混合体。修改为管道分隔
  • 将路由命名为
    json
    而不是
    index
  • ingreients2
    是一个字符串,需要是json才能作为json返回
  • 使用
    jsonify()

  • 从输入示例中,我可以看到没有描述列,那么,您打算从哪里获取该数据呢?好的,我将添加我已更新的完整csv文件,请查看我的csv文件,
    ingredients2
    列包含
    键值和对
    ,因此我想在json数组列表中获取上述数据,请提供任何帮助谢谢先生:)
    import pandas as pd, json, io
    from flask import Flask, render_template, Response, jsonify
    
    app = Flask(__name__)
    
    @app.route('/json')
    def json_so():
        df = pd.read_csv(io.StringIO("""recipe_id|recipe_name|ingredients2
           240488  |  Pork Loin  |   [{"title":"basmati rice","quantity":"1 cup"}, {"title":"mint  leaves","quantity":"1/2teaspoon"}, {"title":"salt","quantity":"as required"}]
           218939  |   Foolproof Rosemary   |    [{"title":"Meat","quantity":"1 kg"}, {"title":"Water","quantity":"1 Glass"}, {"title":"Mirch powder","quantity":"5 -10 Teaspoon"}]
         """), sep="|")
        # key step convert string to actual JSON so when given back as response it's not a string
        df["ingredients2"] = df["ingredients2"].apply(lambda x: json.loads(x))
        # just use jsonify() it's simpler
        return jsonify(df[['recipe_id', 'recipe_name', 'ingredients2']].to_dict(orient="records"))
    
    
    if __name__ == '__main__':
        app.run(debug=True)