[英]Removing the enumerator from json file using Python
The following code generates a json file, however, I need to get rid of the enumerator element in the output (ie "1":, "2":, etc.) .下面的代码生成一个 json 文件,但是,我需要去掉 output 中的枚举器元素(即“1”:、“2”:等) 。 It looks like a dumb question but I'm totally confused!
这看起来像一个愚蠢的问题,但我完全糊涂了!
The output looks like this: output 看起来像这样:
{
"1": {
"found": "Alaska",
"resolved as": " alaska",
"gazetteer": " {com.novetta.clavin.gazetteer.LazyAncestryGeoName@59b62d}",
"position": " 795",
"confidence": " 1.000000",
"fuzzy": " false",
"lon": " -150.00028",
"lat": " 64.00028"
}, ...
And here is the code:这是代码:
import json
filename = 'output.txt'
dict1 = {}
fields = ['found', 'resolved as', 'gazetteer', 'position', 'confidence', 'fuzzy', 'lon', 'lat' ]
with open(filename) as fh:
l = 1
for line in fh:
# reading line by line from the text file
description = list( line.strip().split(','))
# for output see below
print(description)
# for automatic creation of id for each employee
sno = '' + str(l)
# loop variable
i = 0
# intermediate dictionary
dict2 = {}
while i<len(fields):
# creating dictionary for each employee
dict2[fields[i]]= description[i]
i = i + 1
# appending the record of each employee to
# the main dictionary
dict1[sno]= dict2
l = l + 1
# creating json file
out_file = open("test2.json", "w")
json.dump(dict1, out_file, indent = 4)
out_file.close()
To get rid of the enumerator, there should only be one dictionary.要摆脱枚举器,应该只有一本字典。 Here is the new code which converts a text file to json:
这是将文本文件转换为 json 的新代码:
import json
filename = 'output.txt'
fields = ['found', 'resolved as', 'gazetteer', 'position', 'confidence', 'fuzzy',
'lon', 'lat' ]
dic1 = {}
with open(filename) as fh:
for line in fh:
# reading line by line from the text file
description = list( line.strip().split(','))
print(description)
for lines in description:
for key in fields:
for value in description:
dic1[key] = value
description.remove(value)
break
#print (str(dic1))
json_string = json.dumps(dic1)
print(json_string)
Now, the output in the json file looks like this (without the enumerator (ie key):现在,json 文件中的 output 看起来像这样(没有枚举器(即键):
{"found": "Alaska", "resolved as": " alaska", "gazetteer": " {com.novetta.clavin.gazetteer.LazyAncestryGeoName@59b62d}", "position": " 56332", "confidence": " 1.000000", "fuzzy": " false", "lon": " -150.00028", "lat": " 64.00028"}
{“找到”:“阿拉斯加”,“解析为”:“阿拉斯加”,“地名词典”:“{com.novetta.clavin.gazetteer.LazyAncestryGeoName@59b62d}”,“位置”:“56332”,“信心”: “1.000000”、“模糊”:“假”、“lon”:“-150.00028”、“lat”:“64.00028”}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.