-1

I have a csv file with 3 fields. I want to create a json file based on the table custom format. I want to use the json file in dash cytoscape.

I have tried to use pandas as a data frame and change the data frame to a json format. I sawthis question. Beacause of the different json format different this question i could not use the answer. CSV table:

DISTRICT,MONTH
B2,2
A7,5
A1,9

...

I want to convert the table to json with the below format:

[           {'data': {'id': 'B2', 'label': 'B2'}},
            {'data': {'id': 'A7', 'label': 'A7'}},
            {'data': {'id': 'A1', 'label': 'A1'}},
            {'data': {'id': '2', 'label': '2'}},
            {'data': {'id': '5', 'label': '5'}},
            {'data': {'id': '9', 'label': '9'}},

            {'data': {'source': 'B2', 'target': '2'}},
            {'data': {'source': 'A7', 'target': '5'}},
            {'data': {'source': 'A1', 'target': '9'}}
        ]
BBG_GIS
  • 306
  • 5
  • 17
  • it looks like 2 fields; what have you tried so far and did it fail somewhere? – David May 23 '21 at 06:16
  • @DavidS yes. It's two fields – BBG_GIS May 23 '21 at 06:17
  • I've tried to use pandas as a dataframe and change it to a json file. – BBG_GIS May 23 '21 at 06:21
  • the format doesnt relate to the CSV you have posted in your question, can you provide more info of what you are trying to do? why some ids use the first column and some the second one, what is the target column, etc... – Isma May 23 '21 at 06:34

1 Answers1

1

These code should do the job. Pandas might make it a bit easier if you do some fancy analysis with the data. I am not a fan (since it often gets me into unnecessary tech details, mixed with version confusions) so I stick with the Python built in packages.

import csv
import json

with open('yourcsv.csv') as csvfile:
    labels = []
    mappings = []
    csvreader = csv.reader(csvfile, delimiter=',')
    # skips your header
    next(csvreader)
    for row in csvreader:
        labels.append({
            'data': {'id': row[0], 'label': row[0]},
            'data': {'id': row[1], 'label': row[1]}
        })
        mappings.append({
            'data': {'source': row[0], 'target': row[1]}
        })

with open('yourjson.json', 'w') as f:
    # indent does the prettify
    json.dump(labels + mappings, f, indent=4)
Duo Tao
  • 56
  • 5
  • 1
    Thanks. I use your code and change it.IT works. you missed labels.append({ 'data': {'id': row[1], 'label': row[1]}. }) – BBG_GIS May 23 '21 at 06:43