CSV to JSON blocks in Python

Asked by At

I have the following csv file.

Occurrences,post_title,ID, System
1, Test 7, 34, Abc
2, Test 9, 55, Xyz
5, Test 11, 87, Pqy
7, Test 3, 71, Cde

Ask: I want to iterate through a loop and send each row as JSON block to an API. For example, first iteration I want to send as following. {"occurrences": "1", "post_title": "Test 7", "ID" : "34", "System" : "Abc"}

The second iteration I want to send the following. {"occurrences": "2", "post_title": "Test 9", "ID" : "55", "System" : "Xyz"}

and so forth......

Could you please help in Python the best way to achieve this?

3 Answers

1
Siddhant Kaushal On Best Solutions

This might help you.. csv.DictReader will give you a ordered dict :)

import csv
import json
input_file = csv.DictReader(open("testing_sid.csv"))
for row in input_file:
    out = json.dumps(row)
    print(out)

OUTPUT :-

{"Occurrences": "1", "post_title": " Test 7", "ID": " 34", "System": " Abc"}
{"Occurrences": "2", "post_title": " Test 9", "ID": " 55", "System": " Xyz"}
{"Occurrences": "5", "post_title": " Test 11", "ID": " 87", "System": " Pqy"}
{"Occurrences": "7", "post_title": " Test 3", "ID": " 71", "System": " Cde"}
0
Nerd_Joe On

I think this may solve your problem

import pandas as pd
import json
def get_json(csv_path):
    tabel = pd.read_csv(csv_path)
    row_list = tabel.to_dict('records')
    result = json.dumps(row_list)
    return result
0
DYZ On

I would use pandas that happily integrates CSV and JSON support:

import pandas as pd
df = pd.read_csv("your_file.csv")
result = df.apply(lambda x: x.to_json(), axis=1).tolist()
#['{"Occurrences":1,"post_title":" Test 7","ID" ... "System":" Cde"}']