jhjanicki jhjanicki - 1 month ago 4
JSON Question

convert a csv file to json where one of the fields can be converted into an array

Currently I am working on putting some data together as a csv file with the intention of converting it into a json object. For example, this is what a couple rows of my data looks like (the first row is the header with the titles of each column)

Scientific Name | Threats | Range States
Psittacula eupatria | illegal trade, habitat loss | Afghanistan, Bangladesh, Bhutan
Cacatua alba | illegal trade, overharvesting|Indonesia


I was wondering for the fields where there are more than one element associated with it (for example, for the first row for Threats there is illegal trade, habitat loss and for Range States there is Afghanistan, Bangladesh, Bhutan) is there a way to store these to arrays while converting the csv file to json?

so the json would look like this?

[
{"Scientific Name": "Psittacula eupatria",
"Threats":["illegal trade", "habitat loss"],
"Range States":["Afghanistan","Bangladesh","Bhutan"]
},
{"Scientific Name": "Cacatua alba",
"Threats":["illegal trade", "overharvesting"],
"Range States":["Indonesia"]
}
]

Answer

Most certainly.

Once you have the entire string "illegal trade, habitat loss" in your code as a variable, you can simply split it on the commas (including the space). How you do it is based on what language/framework you're working with.

Javascript:

var csvCell = { ... };
var cellArray = csvCell.split(", ");
// cellArray contains ["illegal trade", "habitat loss"]

Python / Ruby:

csv_cell = { ... }
cell_array = csv_cell.split(", ")
# cell_array contains ["illegal trade", "habitat loss"]

Go:

import "strings"

var csvCell string = { ... }
var cellArray = strings.Split(csvCell, ", ")

etc. etc.