简体   繁体   English

如何以正确的格式将 CSV 转换为 Json

[英]How to convert CSV to Json in proper format

Hi I am new to csv conversion to Json using python.嗨,我是使用 python 将 csv 转换为 Json 的新手。 I am trying to convert a csv file to json format and return the response in a function call but getting slash characters.我正在尝试将 csv 文件转换为 json 格式并在函数调用中返回响应,但得到斜杠字符。

When i open CSV File using the Notepad++ this is how the data looks当我使用Notepad++打开 CSV 文件时,这是数据的样子

"Sno ","Name","Age ","City"
"1","Alex","27","Newyork"
"2","Smith","25","Los angeles"
"3","austin","26","Calfornia

Expected output:预期输出:

[
    {
        "Sno ": "1",
        "Name": "Alex",
        "Age ": "27",
        "City": "Newyork"
    },
    {
        "Sno ": "2",
        "Name": "Smith",
        "Age ": "25",
        "City": "Los angeles"
    },
    {
        "Sno ": "3",
        "Name": "austin",
        "Age ": "26",
        "City": "Calfornia"
    }
]

Python code:蟒蛇代码:

def refresh():
    # reading the header from the csv file in an array
    with open(r"C:\Users\prasanna.kommuri\example_flask_application\target_py_files\data_file.csv", "r") as f:
        reader = csv.reader(f)
        csv_header_row = next(reader)

    #Reading the content from the csv file
    json_data = [json.dumps(d) for d in csv.DictReader(open(r"C:\Users\prasanna.kommuri\example_flask_application\target_py_files\data_file.csv", 'r'), fieldnames=csv_header_row, quotechar='"', delimiter=',',
                 quoting=csv.QUOTE_ALL, skipinitialspace=True)]
    return jsonify(json_data)

Actual output:实际输出:

[
   "{\"Sno \": \"Sno \", \"Name\": \"Name\", \"Age \": \"Age \", \"City\": \"City\"}",
   "{\"Sno \": \"1\", \"Name\": \"Alex\", \"Age \": \"27\", \"City\": \"Newyork\"}",
   "{\"Sno \": \"2\", \"Name\": \"Smith\", \"Age \": \"25\", \"City\": \"Los angeles\"}",
   "{\"Sno \": \"3\", \"Name\": \"austin\", \"Age \": \"26\", \"City\": \"Calfornia\"}"
]

Can someone please help where i am going wrong or any suggestions/responses would be helpful Thank you in advance.有人可以帮助我出错的地方,或者任何建议/回复都会有所帮助,提前谢谢。

import json, csv

with open(r'U:\foobar.csv', 'r', newline='') as f:
    print(json.dumps(list(csv.DictReader(f)), indent=4))

prints印刷

[
    {
        "Sno ": "1",
        "Name": "Alex",
        "Age ": "27",
        "City": "Newyork"
    },
    {
        "Sno ": "2",
        "Name": "Smith",
        "Age ": "25",
        "City": "Los angeles"
    },
    {
        "Sno ": "3",
        "Name": "austin",
        "Age ": "26",
        "City": "Calfornia"
    }
]

or to output to file或输出到文件

with open(r'U:\foobar.csv', 'r', newline='') as fin:
    with open(r'U:\foobar.json', 'w') as fout:
        json.dump(list(csv.DictReader(f)), fout, indent=4))

Please check this.请检查这个。

import csv
import json

def refresh():
    # reading the header from the csv file in an array
    data_dict_list = []
    with open(r"result.csv", "r") as f:
        reader = csv.reader(f)
        csv_header_row = next(reader)

        for data in reader:
            data_dict_list.append(
                {
                    csv_header_row[0]: data[0],
                    csv_header_row[1]: data[1],
                    csv_header_row[2]: data[2],
                    csv_header_row[3]: data[3],
                 }
            )

        return  json.dumps(data_dict_list, indent=4)

result = refresh()
print(result)

Output:输出:

[
    {
        "Sno ": "1",
        "Name": "Alex",
        "Age ": "27",
        "City": "Newyork"
    },
    {
        "Sno ": "2",
        "Name": "Smith",
        "Age ": "25",
        "City": "Los angeles"
    },
    {
        "Sno ": "3",
        "Name": "austin",
        "Age ": "26",
        "City": "Calfornia"
    }
]

Disclaimer this is not explaining why your code is failing, but is giving an alternative solution using pandas , as you mentioned you were open to new solutions as well.免责声明,这并没有解释您的代码失败的原因,而是使用pandas提供了替代解决方案,正如您提到的,您也对新解决方案pandas开放态度。

>>> import pandas as pd
>>> from io import StringIO  # that's just to pretend I have a .csv file like yours

>>> df = pd.read_csv(StringIO('''"Sno ","Name","Age ","City" 
"1","Alex","27","Newyork" 
"2","Smith","25","Los angeles" 
"3","austin","26","Calfornia"'''))                                                                                                                 

>>> print(df.to_json(orient="records", indent=4))                                                                                                                      
[
    {
        "Sno ":1,
        "Name":"Alex",
        "Age ":27,
        "City ":"Newyork "
    },
    {
        "Sno ":2,
        "Name":"Smith",
        "Age ":25,
        "City ":"Los angeles "
    },
    {
        "Sno ":3,
        "Name":"austin",
        "Age ":26,
        "City ":"Calfornia"
    }
]

So in a nutshell, assuming you have a path leading to your .csv file called path_to_csv , it's a 1-liner:因此,简而言之,假设您有一条通向名为path_to_csv的 .csv 文件的path_to_csv ,它是一个 1-liner:

json_data = pd.read_csv(path_to_csv).to_json(orient="records", indent=4)

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

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