python - 如何在 Python 中从 CSV 文件中提取 JSON 对象?

标签 python json python-2.7 csv

我正在从 csv 文件(不是整个文件)中提取列值。这些值采用 JSON 格式,如下所示:

{u'Other': {'Text': 'Telephone', 'start': 45, 'end': 54, u'value': u'contact information'}}

我可以使用以下代码将这些值放入列表中(json对象= [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;不是列表?

最佳答案

这应该可以满足您的要求:

#!/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
    }
}

关于python - 如何在 Python 中从 CSV 文件中提取 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33424238/

相关文章:

python - 如何挤压除一支 torch 之外的所有 torch ?

python - 将简单列表转换为字典(在 python 中)

python - 没有名为 '_plotly_utils' 的模块

javascript - Json 数据未呈现到 DOM

json - 如何在Grails中将域及其关系呈现为JSON

python - 为什么 zip 会更改我的列表?

python - Django REST 仅列表(无详细信息)ViewSet

php - 如何在 PHP 中从 Google Maps Direction API 解码折线

python - PyCharm 无法识别我的 Python 安装路径

python - 如何访问每个模块类中的对象? Python