简体   繁体   English

Python csv to json using pandas - csv columns to nested json

[英]Python csv to json using pandas - csv columns to nested json

Python 3.8.5 with Pandas 1.1.3 Python 3.8.5 与 Pandas 1.1.3

I have a csv file with columns: name, city, state, and zipcode.我有一个 csv 文件,其中包含以下列:名称、城市、state 和邮政编码。 I need to convert to json with the city, state, and zipcode column values inside an object called residence.我需要将城市、state 和 object 中的邮政编码列值转换为 json,称为住宅。

For example:例如:

CSV file CSV 文件

Name        City    State  Zipcode
John Doe    Akron   OH     44140

I need the JSON output to be structured like:我需要 JSON output 的结构如下:

{
    "name": "John Doe",
    "residence" : 
        {
        "city": "Akron",
        "state": "OH",
        "zipcode": 44140
        }
}

I currently use Pandas to convert csv to json using the following code:我目前使用 Pandas 使用以下代码将 csv 转换为 json:

import pandas as pd

csv_file = pd.DataFrame(pd.read_csv("data.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("data.json", orient = "records", lines = True, date_format = "iso", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)

As-is, that just converts each column to a json key:value.按原样,这只是将每一列转换为 json 键:值。

How can I add to this code to achieve my desired output?如何添加到此代码以实现我想要的 output?

IIUC try creating the nested object row-wise first, then creating the JSON: IIUC 尝试首先按行创建嵌套的 object,然后创建 JSON:

import pandas as pd

csv_file = pd.read_csv("data.csv", sep=",",
                       header=0, index_col=False)

# Create Nested dict (Object)
csv_file['Residence'] = csv_file[['City', 'State', 'Zipcode']].apply(
    lambda s: s.to_dict(), axis=1
)
# Write out Name and Residence Only
csv_file[['Name', 'Residence']].to_json("data.json", orient="records",
                                        lines=True, date_format="iso",
                                        double_precision=10, force_ascii=True,
                                        date_unit="ms", default_handler=None)

data.csv数据.csv

Name,City,State,Zipcode
John Doe,Akron,OH,44140
Jane Smith,Los Angeles,California,90005

data.json数据.json

{"Name":"John Doe","Residence":{"City":"Akron","State":"OH","Zipcode":44140}}
{"Name":"Jane Smith","Residence":{"City":"Los Angeles","State":"California","Zipcode":90005}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM