Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

one_liners > CSV to json may be incorrect #231

Open
DingJunyao opened this issue Dec 23, 2021 · 0 comments
Open

one_liners > CSV to json may be incorrect #231

DingJunyao opened this issue Dec 23, 2021 · 0 comments

Comments

@DingJunyao
Copy link

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"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant