如何在python中通过嵌套键对JSON对象进行分组

时间:2018-03-09 10:35:10

标签: python json nested

我已将CSV文件传递给JSON。我有这样的事情:

[{
      "Intent": "About",
      "Texto": "quien"
   },
 {
      "Intent": "NP_Contacto",
      "Texto": "atencion"
   },
   {
      "Intent": "NP_Contacto",
      "Texto": "informacion?"
   },
   {
      "Intent": "NP_Contacto",
      "Texto": "hablar"
   },
   {
      "Intent": "NP_Contacto",
      "Texto": "numero"
   }]

但我想要这个:

[{             "intent": "NP_Contacto",
                "texto": [{
                        "text": "telefono"
                    },
                    {
                        "text": "hablar"
                    },
                    {
                        "text": "número"
                    },
                    {
                        "text": "atención"
                    },
                    {
                        "text": "informacion"
                    }
                ]
            },
{
      "Intent": "About",
      "Texto": "quien"
   },

]

我用来创建它的代码是:

reader = csv.DictReader(csvfile, fieldnames=("Texto", "Intent")) 
fieldnames = ("Texto", "Intent") 

output = [] 

for each in reader: 
    row = {} for field in fieldnames: 
    row[field] = each[field] 
    output.append(row) 

json.dump(output, jsonfile, indent=3, sort_keys=True)

1 个答案:

答案 0 :(得分:-1)

我认为你只是想重新组合它 所以尝试类似的事情:

for i in json:
    for j,k in i.items():
        ...