我从csv文件(而不是整个文件)中提取列值。值为JSON格式,如下所示:
{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}
我可以使用以下代码将这些值放入列表中(json objects = [6]表示我的csv文件中的第七列):
import csv
with open('C:\\file\\path\\to\\csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
json_objects = [6]
for row in reader:
single_json = list(row[i] for i in json_objects)
print ', '.join(single_json)
如何将列提取为JSON' s;不是列表?
答案 0 :(得分:2)
这应该做你想要的:
#!/usr/bin/python
import csv
import json
with open('csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
single_json = row[6]
single_json = single_json.replace("u'", "'")
single_json = single_json.replace("'", '"')
data = json.loads(single_json)
print json.dumps(data, indent=4)
名为“csv”的输入文件:
2840,test_category_labeling_highlight,84,3635,0,Other,"{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}",8,7,FALSE
输出:
{
"Other": {
"Text": "Telephone",
"end": 54,
"value": "contact information",
"start": 45
}
}