Skip to content

one_liners > CSV to json may be incorrect #231

@DingJunyao

Description

@DingJunyao

In the section:

python -c "import csv,json;print json.dumps(list(csv.reader(open('csv_file.csv'))))"

I tried the code in the paragraph with both Python 2 and 3(with modification), sample:

a,b,c,d,e
1,2,3,4,5
f,w,e,r,t
`,1,2,3,4

it returns like:

[["a", "b", "c", "d", "e"], ["1", "2", "3", "4", "5"], ["f", "w", "e", "r", "t"], ["`", "1", "2", "3", "4"]]

Not seems like JSON. So maybe it's wrong.

However, I don't know the sample of the CSV and output in the paragraph, so I didn't create a pull request.

I have code which works, but not in one line:

import csv
import json


def csv_to_json(file_path):
    ret_list = []
    with open(file_path, 'r') as f:
        csv_list = list(csv.reader(f))
        for col in csv_list[1:]:
            ret_list.append(dict(zip(csv_list[0], col)))
    return json.dumps(ret_list)

print(csv_to_json('csv_file.csv'))

returns (with CSV above):

[{"a": "1", "b": "2", "c": "3", "d": "4", "e": "5"}, {"a": "f", "b": "w", "c": "e", "d": "r", "e": "t"}, {"a": "`", "b": "1", "c": "2", "d": "3", "e": "4"}]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions