I would like to output the following text file to the JSON format displayed below using Python.
I am not sure where to begin, but I hope that my problem is simple to understand.
input.txt
Name 1, FeatureServer, thisIsALink, layer 1, layer 2
Name 2, FeatureServer, thisIsALink, layer 1
Name 3, MapServer, thisIsALink, layer 1, layer 2
Name 4, FeatureServer, thisIsALink, layer 1, layer 2
Name 5, FeatureServer, thisIsALink, layer 1, layer 2, layer 3
output.json
{
"Name 1": {
"type": "FeatureServer",
"url": "thisIsALink",
"layer(s)": {
"1": "layer 1",
"2": "layer 2"
}
},
"Name 2": {
"type": "FeatureServer",
"url": "thisIsALink",
"layer(s)": {
"1": "layer 1"
}
},
"Name 3": {
"type": "FeatureServer",
"url": "thisIsALink",
"layer(s)": {
"1": "layer 1",
"2": "layer 2"
}
},
"Name 4": {
"type": "FeatureServer",
"url": "thisIsALink",
"layer(s)": {
"1": "layer 1",
"2": "layer 2"
}
},
"Name 5": {
"type": "FeatureServer",
"url": "thisIsALink",
"layer(s)": {
"1": "layer 1",
"2": "layer 2",
"3": "layer 3"
}
}
}
I have tried following a tutorial from GeeksforGeeks
But I haven’t quite figured out how to make it work for my situation.
3
Answers
Here is a small script that does just that:
The problem is that your "layers" need to be nested in json, and there’s no way to represent that in csv. If it is implied that columns 4, 5 (and beyond) should be nested, you could address that programmatically.
I assume this is the tutorial you are referring to :
https://www.geeksforgeeks.org/convert-csv-to-json-using-python/
Here is one way to do it, based on the infromation you’ve provided:
Play with it, see if that is what you’re looking for!