How to Convert csv to json with separate by '|'

Viewed 99

I have csv below

id,name,style
1,ma,Exp|Nar|Arg
2,bi,EXp
3,El,rg|Exp

Code is below

import csv
import json

json_data = [json.dumps(d) for d in csv.DictReader(open('file.csv'))]

My out

['{"id": "1", "name": "ma", "style": "Exp|Nar|Arg"}',
 '{"id": "2", "name": "bi", "style": "EXp"}',
 '{"id": "3", "name": "El", "style": "rg|Exp"}']

I need output as

['{"id": "1", "name": "ma", "style": ["Exp","Nar","Arg"}',
 '{"id": "2", "name": "bi", "style": ["EXp"]}',
 '{"id": "3", "name": "El", "style": ["rg","Exp"]}']

in Expected out style has to be in list format

2 Answers

You can add a step for processing you CSV data. The simplest way may be to replace | with , using String.replace(), built-in function. You can also extract the style part and make an equivalent string with something like this:

data = """id,name,style
1,ma,Exp|Nar|Arg
2,bi,EXp
3,El,rg|Exp
"""
for line in data.splitlines()[1:]:
    style = line.split(',')[-1]
    style = f'[{style.replace("|", ",")}]'

It reads each line beginning from the second one (first one is just titles), and since style is the last part you can extract it using String.split() and its index -1.

replace | with , and wrap row["style"] in [] before serializing the object to a JSON formatted string.

import csv
import json

json_data = []
with open("file.csv") as csvfile:
    for row in csv.DictReader(csvfile):
        row["style"] = [row["style"].replace('|', ',')]
        json_data.append(row)

json_data = [json.dumps(d) for d in json_data]

print(json_data)

Output:

[
    '{"id": "1", "name": "ma", "style": ["Exp,Nar,Arg"]}',
    '{"id": "2", "name": "bi", "style": ["EXp"]}',
    '{"id": "3", "name": "El", "style": ["rg,Exp"]}',
]
Related