我尝试使用python从CSV创建JSON。我遇到的这个问题是一种从数据中分离标题的方法。我目前的代码是:
import csv
import json
with open('input.csv') as f:
columns = ("Column 1", "Column 2")
reader = csv.DictReader(f, columns)
rows = list(reader)
with open('output.json', 'w') as f:
json.dump(rows, f, indent=4)
但是会返回
[
{
"Column 2": null,
"Column 1": "Title"
},
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
而不是
[
"Title1": {
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
}
]
下面是CSV的参考示例:
Title
data1, data2
data3, data4
data5, data6
Title2
data1, data2
data3, data4
data5, data6
答案 0 :(得分:0)
您需要将数据作为读取消息发送到其他结构。
类似的东西:
data={}
with open('/tmp/f.csv') as f:
reader=csv.reader(f)
for sl in (row for row in reader):
if len(sl)==1:
key=sl[0]
data[key]=[]
else:
data[key].append({"Column {}".format(i):e for i, e in enumerate(sl,1)})
>>> json.dumps(data, f, indent=4)
{
"Title2": [
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
],
"Title": [
{
"Column 2": " data2",
"Column 1": "data1"
},
{
"Column 2": " data4",
"Column 1": "data3"
},
{
"Column 2": " data6",
"Column 1": "data5"
}
]
}
答案 1 :(得分:0)
您需要自己构建嵌套数据结构,而不仅仅使用list
。这是你可以做到的一种方式:
import csv
import json
with open('input.csv') as f:
columns = ("Column 1", "Column 2")
reader = csv.DictReader(f, columns)
tree = {}
for row in reader:
if row["Column 2"] is None:
current = []
tree[row["Column 1"]] = current
else:
current.append(row)
当找到“标题”行(第二列为空的行)时,会向树中添加一个新列表。此列表中将添加更多行,直到出现另一个“标题”行,并启动新列表。
答案 2 :(得分:0)
你可以这样做吗?
<?php
while ($rowG = oci_fetch_array($stid, OCI_RETURN_NULLS)) {
?>
<tr>
<td><?php echo $rowG[2]; ?></td>
<td><?php echo $rowG[1]; ?></td>
<td><?php echo $rowG[0]; ?></td>
<td><?php echo $rowG[3]; ?></td>
<td><?php echo '<a href="./consultation.php?Login='.$rowG[2].'"> Link </a>'; ?></td>
</tr>
<?php
}
?>
返回:
titles = ['Title', 'Title2']
output = {}
for line in f:
if line[0] in titles:
title = line[0]
output[title] = {}
output[title]["Column 1"] = []
output[title]["Column 2"] = []
else:
output[title]["Column 1"].append(line[0])
output[title]["Column 2"].append(line[1])