【问题标题】:Is there a python function for creating a nested JSON file from a DF?是否有用于从 DF 创建嵌套 JSON 文件的 python 函数?
【发布时间】:2019-10-23 03:53:46
【问题描述】:

我正在尝试从最终 JSON 文件应具有的架构开始构建数据框。

架构如下:

[{"plant": ,
  "at": ,
  "products": [{
          "product": ,
          "quantity": ,
      }]

工厂应该是字符串,at应该是日期ISO8601,产品应该是字符串,数量应该是整数。

我构建的数据框如下:

Plant    At         Products    Product    Quantity
XXX    2019-06-07   products    product1     4
YYY    2019-06-07   products    product2     -9
ZZZ    2019-06-07   products    product3     2099

现在我正在尝试生成嵌套的 JSON 文件,但我使用的代码无法正常工作

j2 = (df2.groupby(['plant', 'at'], as_index=False)
    .apply(lambda x: x[['product', 'quantity']].to_dict('r'))
    .reset_index()
    .rename(columns={0: 'products'})
    .to_json(orient='columns'))

我得到了这个 JSON

{"plant":{"0":"XXX","1":"YYY","2":"ZZZ"},"at":{"0":"2019-06-07 12:53:13.983775","1":"2019-06-07 12:53:13.983775","2":"2019-06-07 12:53:13.983775"},"products":{"0":[{"product":product1,"quantity":4}],"1":[{"product":product2,"quantity":-9}],"2":[{"product":product3,"quantity":2099}]}}

但实际上这不是我应该生成的格式。

有什么建议吗?有没有办法维护日期的 ISO8601 格式?

【问题讨论】:

    标签: json pandas dataframe nested


    【解决方案1】:

    使用 orient = 'records'

    df2.groupby(['Plant', 'At'])['Product', 'Quantity'].apply(lambda x: x.to_dict('r')).reset_index(name = 'Products').to_json(orient = 'records')
    

    你得到

    [{"Plant":"XXX",
    "At":"2019-05-03",
    "Products":[{"Product":"Product1","Quantity":4}]}]
    

    【讨论】:

      猜你喜欢
      • 2021-02-02
      • 2021-03-20
      • 1970-01-01
      • 2018-06-14
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      相关资源
      最近更新 更多