繁体   English   中英

无法使用 python 从 JSON 生成正确的 csv 文件

[英]Not able to generate a proper csv file from JSON using python

我无法使用以下代码生成正确的 csv 文件。 但是当我单独查询时,我得到了想要的结果。 下面是我的 json 文件和代码

{
"quiz": {
    "maths": {
      "q2": {
            "question": "12 - 8 = ?",
            "options": [
                "1",
                "2",
                "3",
                "4"
            ],
            "answer": "4"
        },
        "q1": {
            "question": "5 + 7 = ?",
            "options": [
                "10",
                "11",
                "12",
                "13"
            ],
            "answer": "12"
        }
        
    },
    "sport": {
        "q1": {
            "question": "Which one is correct team name in NBA?",
            "options": [
                "New York Bulls",
                "Los Angeles Kings",
                "Golden State Warriros",
                "Huston Rocket"
            ],
            "answer": "Huston Rocket"
        }
    }        
}

}

import json
import csv

# Opening JSON file and loading the data
# into the variable data
with open('tempjson.json', 'r') as jsonFile:
    data = json.load(jsonFile)
    flattenData=flatten(data)

employee_data=flattenData

# now we will open a file for writing
data_file = open('data_files.csv', 'w')

# create the csv writer object
csv_writer = csv.writer(data_file)

# Counter variable used for writing 
# headers to the CSV file
count = 0

for emp in employee_data:
    if count == 0:

        # Writing headers of CSV file
        header = emp
        csv_writer.writerow(header)
        count += 1

    # Writing data of CSV file
    #csv_writer.writerow(employee_data.get(emp))

data_file.close()

执行上述代码后,我得到如下信息:

在此处输入图像描述

我不明白我做错了什么。 我正在展平我的 json 文件,然后尝试将其更改为 csv

您可以使用 Pandas 数据帧轻松操作 JSON 并将其保存到 CSV。 我不确定您想要的 CSV 应该是什么样子,但以下代码会生成一个 CSV 列问题、选项和答案。 它会在按字母顺序排列的列表中生成一个包含测验名称和问题编号的索引列(您的 JSON 是无序的)。 当添加更多不同的测验和问题时,下面的代码也将起作用。

也许在 Python 中本地转换它在性能方面更好,但使用 Pandas 进行操作更容易。

import pandas as pd

# create Pandas dataframe from JSON for easy manipulation
df = pd.read_json("tempjson.json")

# create result dataframe
df_result = pd.DataFrame()

# Get nested dict from each dataframe row
for index, row in df.iterrows():
    
    # Convert it into a new dataframe
    df_temp = pd.DataFrame.from_dict(df.loc[index]['quiz'], orient='index')
    # Add name of quiz to index
    df_temp.index = index + ' ' + df_temp.index
    # Append row result to final dataframe
    df_result = df_result.append(df_temp)
    
# Optionally sort alphabetically so questions are in order
df_result.sort_index(inplace=True)

# convert dataframe to CSV
df_result.to_csv('quiz.csv')

CSV

根据要求更新:使用扁平 JSON 导出到 CSV:

import json
import csv
from flatten_json import flatten
import pandas

# Opening JSON file and loading the data
# into the variable data
with open("tempjson.json", 'r') as jsonFile:
    data = json.load(jsonFile)
    flattenData=flatten(data)
    
    
df = pd.DataFrame.from_dict(flattenData, orient='index')    

# convert dataframe to CSV
df.to_csv('quiz.csv', header=False)    

结果如下 CSV (不确定您想要的结果是什么,因为您没有在问题中提供所需的结果)。

csv扁平化输出

暂无
暂无

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

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