Fundamentals 6 min read

Convert JSON to CSV and Sort the CSV by Column Using Python

This guide demonstrates how to transform a JSON array into a CSV file with pandas, then sort the resulting CSV by specific columns using two different Python approaches, providing complete code snippets and explanations for each step.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Convert JSON to CSV and Sort the CSV by Column Using Python

Function points: generate CSV from JSON and sort CSV by a column.

Dependencies: pandas and csv modules.

Sample JSON data is a list of dictionaries with fields id, type, num, createTime, price, desc, symbol, nickname, headImgUri.

Code to convert JSON to CSV:

def json_to_csv():
    id = []
    type = []
    num = []
    createTime = []
    price = []
    desc = []
    symbol = []
    nickname = []
    headImgUri = []

    for i in range(len(yuncangData)):
        id.append(yuncangData[i]["id"])
        type.append(yuncangData[i]["type"])
        num.append(yuncangData[i]["num"])
        createTime.append(yuncangData[i]["createTime"])
        price.append(yuncangData[i]["price"])
        desc.append(yuncangData[i]["desc"])
        symbol.append(yuncangData[i]["symbol"])
        nickname.append(yuncangData[i]["nickname"])
        headImgUri.append(yuncangData[i]["headImgUri"])

    dataframe = pd.DataFrame({
        'id': id,
        'type': type,
        "num": num,
        "createTime": createTime,
        "price": price,
        "desc": desc,
        "symbol": symbol,
        "nickname": nickname,
        "headImgUri": headImgUri,
    })
    dataframe.to_csv("read.csv", index=False, sep=',')

Two sorting methods are provided.

Method one sorts by a specific index (the fifth column) using the csv module:

def sort_index_csv():
    with open('read.csv', newline='') as f_input:
        csv_input = csv.reader(f_input)
        header = next(csv_input)
        data = list(csv_input)
    data.sort(key=lambda x: ((x[5]), x[0]))
    with open('sort_after.csv', 'w', newline='') as f_output:
        csv_output = csv.writer(f_output)
        csv_output.writerow(header)
        csv_output.writerows(data)

if __name__ == '__main__':
    json_to_csv()
    sort_index_csv()

Method two sorts by a column (the sixth column) in descending order:

# 按 列 进行排序
def sort_csv():
    data = csv.reader(open('read.csv'), delimiter=',')
    print(data)
    next(data)  # 从第二行开始写入
    sortedlist = sorted(data, key=lambda x: x[6], reverse=True)  # 按照第6列进行排序
    print(sortedlist)

    with open("sort_after.csv", "w", newline='') as f:
        fileWriter = csv.writer(f, delimiter=',')
        for row in sortedlist:
            print(row)
            fileWriter.writerow(row)
        f.close()

if __name__ == '__main__':
    json_to_csv()  # 原始数据转csv
    sort_csv()  # 按照类型进行排序(即第6列)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonJSONCSVSorting
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.