python generate json output from input file -


i have file similar input :

lin1,line2,line3 lin1,line2,line3 lin1,line2,line4 

and need convert json python. example, output should this:

{     "localport_starts_from": 1080,     "config": [         {             "1": "lin1",             "2": "line2",             "3": "line3"         },         {             "1": "lin1",             "2": "line2",             "3": "line3"         },         {             "1": "lin1",             "2": "line2",             "3": "line3"         }     ] } 

i have never worked json library, can show me example of how make this?

use csv module parse input , json dump parsing.

with open(input_file) f:     rows = list(csv.reader(f))  # rows list of lists, each inner list contains values formerly separated commas # e.g. [["lin1", "line2", "line3"], ...]  # enumerate(row, 1) returns generator of [(1, "lin1"), (2, "line2")...] row_dicts = [{str(i): v i, v in enumerate(row, 1)} row in rows]  # gather rest of stuff dict # ....  result_dict["config"] = row_dicts  open(output_file, 'w') f:      json.dump(result_dict, f) 

Popular posts from this blog