简体   繁体   English

将 csv 转换为 json 然后在 javascript 中解析

[英]converting csv to json and then parsing it in javascript

I have a python script which converts a csv file to json.我有一个 python 脚本,它将 csv 文件转换为 json。

import csv
import json

# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):
    
    # create a dictionary
    data = {}
    
    # Open a csv reader called DictReader
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        
        # Convert each row into a dictionary
        # and add it to data
        for rows in csvReader:
            
            # Assuming a column named 'No' to
            # be the primary key
            key = rows['issue']
            data[key] = rows

    # Open a json writer, and use the json.dumps()
    # function to dump data
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))
        
# Driver Code

# Decide the two file paths according to your
# computer system
csvFilePath = r'Names.csv'
jsonFilePath = r'Names.json'

# Call the make_json function
make_json(csvFilePath, jsonFilePath)

my csv file is like this我的 csv 文件是这样的

issue, summary, desc
A1, summ1, desc1
A2, summ2, desc2 

Once the script is run, I get the following json file脚本运行后,我得到以下 json 文件

{
    "A1": {
        "issue": "A1",
        " summary": " summ1",
        " desc": " desc1"
    },
    "A2": {
        "issue": "A2",
        " summary": " summ2",
        " desc": " desc2 "
    }
}

Now in my javascript application, I want to read this json file and iterate over it.现在在我的 javascript 应用程序中,我想读取这个 json 文件并对其进行迭代。 Sample code in my react application is我的反应应用程序中的示例代码是

import myData from <jsonfile>
console.log(myData['A1'].summary) 

but for this to work I need to know the value A1, A2 etc..但要使其正常工作,我需要知道 A1、A2 等的值。

I am unable to work out how to iterate on this.我无法弄清楚如何对此进行迭代。 Please can someone guide me on what a sample javascript code should look like to work with this json.请有人指导我了解与此 json 一起使用的示例 javascript 代码应该是什么样的。 Operations I want to perform are extract, all issue fields, extract all summary fields etc. Basically work on this json result like it was an array.我要执行的操作是提取、所有问题字段、提取所有汇总字段等。基本上可以处理这个 json 结果,就像它是一个数组一样。

for (const k in myData) {
    console.log(`${myData[k].issue}: ${myData[k][" summary"]}`);
}

You have spaces in your JSON names: you have " summary" instead of "summary" .您的 JSON 名称中有空格:您有" summary"而不是"summary" Fix that, and it will work.修复它,它会工作。

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

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