将文本文件内容输出到JSON Python



我想使用Python将以下文本文件输出为JSON格式。

我不知道从哪里开始,但我希望我的问题简单易懂。

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"
}
}
}

我试着遵循GeeksforGeeks的教程

但我还没有完全弄清楚如何使它适用于我的情况。

这里有一个小脚本可以做到这一点:

import json
output = {}
with open("input.txt", "r") as f:
for line in f:
# Split the line, preserve all layers
name, server, url, *layers = line.rstrip().split(", ")
output[name] = {
"type": server,
"url": url,
"layer(s)": {str(i): layer for i, layer in enumerate(layers, 1)}
}
with open("output.json", "w") as f:
json.dump(output, f, indent=4)

根据您提供的信息,有一种方法可以这样做:

import json
def main():
file = './74724498/input.txt'
output_dict = {}
with open(file) as f:
for line in f:
# Strip the newline character and split the line into a list
line_ls = line.strip().split(", ")
# Create a dictionary for each row:
row_dict = {
line_ls[0]: {
"type": line_ls[1],
"url": line_ls[2],
# Create a dictionary for each layer:
"layer(s)": {str(index): val for index, val in enumerate(line_ls[3:], start=1)}
}
}
# Update the output dictionary with the row dictionary:
output_dict.update(row_dict)

# Write the output dictionary to a json file, indenting the output for readability:
json_string = json.dumps(output_dict, indent=4)
# Write the json string to a file:
with open('json_data.json', 'w') as outfile:
outfile.write(json_string)    

if __name__ == '__main__':
main()

试试吧,看看这是不是你想要的!

问题是你的"图层"需要嵌套在json中,而无法在csv中表示。如果暗示列4、列5(以及以后的列)应该嵌套,您可以通过编程解决这个问题。

我猜这就是你所指的教程:

https://www.geeksforgeeks.org/convert-csv-to-json-using-python/

最新更新