【问题标题】:how to group JSON objects by nested keys in python如何通过python中的嵌套键对JSON对象进行分组
【发布时间】:2018-03-09 10:35:10
【问题描述】:

我已将 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)

【问题讨论】:

  • 请向我们展示您已经尝试过的代码。

标签: python json nested


【解决方案1】:

我认为你只是想重新组合它。
所以试试类似的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2019-03-20
    • 2016-09-10
    • 2021-11-30
    • 2018-02-25
    • 2015-03-31
    • 2011-07-01
    相关资源
    最近更新 更多