如何将CSV转换为嵌套JSON。

huangapple go评论78阅读模式
英文:

How to convert csv to nested json

问题

{
    "order_date": "22/06/2023",
    "data": [
        {
            "customer_id": "A001",
            "customername": "Allan",
            "order_id": "5",
            "total": "50"
        },
        {
            "customer_id": "A002",
            "customername": "Boy",
            "order_id": "2",
            "total": "150"
        }
    ]
}
英文:

I have this csv file and wondering how to display result as expected ?

CSV File

order_date,customer_id,customername,order_id,total
22/06/2023,1,Allan,5,50
22/06/2023,2,Boy,2,150

Code

import JSON
import pandas as pd
df = pd.read_csv(file, dtype=str)

def get_nested_rec(key, grp):
    rec = {}
    rec['customer_id'] = key[0]
    rec['customername'] = key[1]
    rec['order_id'] = key[2]
    rec['total'] = key[3]

    return rec

records = []

for key, grp in df.groupby(['customer_id','customername','order_id','total']):
    rec = get_nested_rec(key, grp)
    records.append(rec)

records = dict(data = records)    

print(json.dumps(records, indent=4))    

Result

{
    "data": [
        {
            "customer_id": "A001",
            "customername": "Allan",
            "order_id": "5",
            "total": "50"
        },
        {
            "customer_id": "A002",
            "customername": "Boy",
            "order_id": "2",
            "total": "150"
        }
    ]
}

Expected result

{
    "order_date":"22/06/2023",
    "data": [
        {
            "customer_id": "A001",
            "customername": "Allan",
            "order_id": "5",
            "total": "50"
        },
        {
            "customer_id": "A002",
            "customername": "Boy",
            "order_id": "2",
            "total": "150"
        }
    ]
}

Another easy way to do ? I am new in this Nested JSON. Thank you.

答案1

得分: 2

请注意,以下是您要翻译的代码部分:

Set `order_date` as index to transform remaining records as data and use `to_dict` to convert the dataframe as dictionary. Finally, export your result to JSON with `to_json`:

records = (df.set_index('order_date').groupby(level='order_date')
             .apply(lambda x: x.to_dict('records'))
             .rename('data').reset_index()
             .to_json(orient='records', indent=4))

如果只有一个日期,您可以使用以下代码:

records = (df.set_index('order_date').groupby(level='order_date')
             .apply(lambda x: x.to_dict('records'))
             .rename('data').reset_index()
             .squeeze().to_json(indent=4))
英文:

Set order_date as index to transform remaining records as data and use to_dict to convert the dataframe as dictionary. Finally, export your result to JSON with to_json:

records = (df.set_index('order_date').groupby(level='order_date')
             .apply(lambda x: x.to_dict('records'))
             .rename('data').reset_index()
             .to_json(orient='records', indent=4))

Output:

>>> records
[
    {
        "order_date":"22\/06\/2023",
        "data":[
            {
                "customer_id":1,
                "customername":"Allan",
                "order_id":5,
                "total":50
            },
            {
                "customer_id":2,
                "customername":"Boy",
                "order_id":2,
                "total":150
            }
        ]
    }
]

If you have one and only one date, you can use:

records = (df.set_index('order_date').groupby(level='order_date')
             .apply(lambda x: x.to_dict('records'))
             .rename('data').reset_index()
             .squeeze().to_json(indent=4))

Output:

>>> records
{
    "order_date": "22/06/2023",
    "data": [
        {
            "customer_id": 1,
            "customername": "Allan",
            "order_id": 5,
            "total": 50
        },
        {
            "customer_id": 2,
            "customername": "Boy",
            "order_id": 2,
            "total": 150
        }
    ]
}

huangapple
  • 本文由 发表于 2023年6月22日 16:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定