You_got_it
You_got_it

Reputation: 341

How can I extract a JSON object from a CSV file in Python?

I am extracting column values from a csv file (not the whole file). The values are in JSON format as follows:

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

I am able to get these values into a list with the following code (json objects = [6] indicates the seventh column in my csv file):

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)

How can I extract the columns as JSON's; not as lists?

Upvotes: 2

Views: 4663

Answers (1)

user3657941
user3657941

Reputation:

This should do what you want:

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

Input file named "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

Output:

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

Upvotes: 4

Related Questions