I need to convert a bunch of csv files to json, using bash and jq v1.6. (I can't use other scripting languages because of a restriction on what script types are allowed to run on the server). Neither JSON or jq are significant parts of my skillset.
I need to use the csv filename as the json object name, read the csv to get the fieldnames from the header, and do a bit of re-mapping to move "owner" to a list (array?) name.
So, take this:
serverset1.csv
location,category,ip,owner
set1rack1,webserver,127.0.0.1,Customer1
set1rack2,appserver,127.0.0.2,Customer1
set1rack1,webserver,127.0.0.3,Customer2
set1rack2,appserver,127.0.0.4,Customer2
to this
[
{
"serverset1":[
{
"Customer1":[
{
"location":"set1rack1",
"category":"webserver",
"address":"127.0.0.1"
},
{
"location":"set1rack2",
"category":"appserver",
"address":"127.0.0.2"
}
],
"Customer2":[
{
"location":"set1rack1",
"category":"webserver",
"address":"127.0.0.3"
},
{
"location":"set1rack2",
"category":"appserver",
"address":"127.0.0.4"
}
]
}
]
}
]
I got as far as this:
filename="serverset1.csv"; \
cat "$filename" | jq --slurp --raw-input --raw-output \
'
split("\n") | .[1:] | map(split(",")) |
map(
{
"location": .[0],
"category": .[1],
"address": .[2],
"owner": .[3]
}
)
'
which yields this:
[
{
"location": "set1rack1",
"category": "webserver",
"address": "127.0.0.1",
"owner": "Customer1"
},
{
"location": "set1rack2",
"category": "appserver",
"address": "127.0.0.2",
"owner": "Customer1"
},
{
"location": "set1rack1",
"category": "webserver",
"address": "127.0.0.3",
"owner": "Customer2"
},
{
"location": "set1rack2",
"category": "appserver",
"address": "127.0.0.4",
"owner": "Customer2"
}
]
but then I hit a syntax wall.
Any help is appreciated.
~Jaimie