[英]converting csv to json and then parsing it in javascript
我有一个 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)
我的 csv 文件是这样的
issue, summary, desc
A1, summ1, desc1
A2, summ2, desc2
脚本运行后,我得到以下 json 文件
{
"A1": {
"issue": "A1",
" summary": " summ1",
" desc": " desc1"
},
"A2": {
"issue": "A2",
" summary": " summ2",
" desc": " desc2 "
}
}
现在在我的 javascript 应用程序中,我想读取这个 json 文件并对其进行迭代。 我的反应应用程序中的示例代码是
import myData from <jsonfile>
console.log(myData['A1'].summary)
但要使其正常工作,我需要知道 A1、A2 等的值。
我无法弄清楚如何对此进行迭代。 请有人指导我了解与此 json 一起使用的示例 javascript 代码应该是什么样的。 我要执行的操作是提取、所有问题字段、提取所有汇总字段等。基本上可以处理这个 json 结果,就像它是一个数组一样。
for (const k in myData) {
console.log(`${myData[k].issue}: ${myData[k][" summary"]}`);
}
您的 JSON 名称中有空格:您有" summary"
而不是"summary"
。 修复它,它会工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.