Asi*_*Ali 8 python json dictionary dynamically-generated
由于问题解释了问题,我一直在尝试生成嵌套的JSON对象.在这种情况下,我有for
循环从字典中获取数据dic
.以下是代码:
f = open("test_json.txt", 'w')
flag = False
temp = ""
start = "{\n\t\"filename\"" + " : \"" +initial_filename+"\",\n\t\"data\"" +" : " +" [\n"
end = "\n\t]" +"\n}"
f.write(start)
for i, (key,value) in enumerate(dic.iteritems()):
f.write("{\n\t\"keyword\":"+"\""+str(key)+"\""+",\n")
f.write("\"term_freq\":"+str(len(value))+",\n")
f.write("\"lists\":[\n\t")
for item in value:
f.write("{\n")
f.write("\t\t\"occurance\" :"+str(item)+"\n")
#Check last object
if value.index(item)+1 == len(value):
f.write("}\n"
f.write("]\n")
else:
f.write("},") # close occurrence object
# Check last item in dic
if i == len(dic)-1:
flag = True
if(flag):
f.write("}")
else:
f.write("},") #close lists object
flag = False
#check for flag
f.write("]") #close lists array
f.write("}")
Run Code Online (Sandbox Code Playgroud)
预期产出是:
{
"filename": "abc.pdf",
"data": [{
"keyword": "irritation",
"term_freq": 5,
"lists": [{
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 2
}]
}, {
"keyword": "bomber",
"lists": [{
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 2
}],
"term_freq": 5
}]
}
Run Code Online (Sandbox Code Playgroud)
但目前我得到的输出如下:
{
"filename": "abc.pdf",
"data": [{
"keyword": "irritation",
"term_freq": 5,
"lists": [{
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 2
},] // Here lies the problem "," before array(last element)
}, {
"keyword": "bomber",
"lists": [{
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 1
}, {
"occurance": 2
},], // Here lies the problem "," before array(last element)
"term_freq": 5
}]
}
Run Code Online (Sandbox Code Playgroud)
请帮助,我试图解决它,但失败了.请不要将其标记为重复,因为我已经检查了其他答案并且根本没有帮助.
编辑1:
输入基本上取自字典,dic
其映射类型<String, List>
为例如:"irritation"=> [1,3,5,7,8]其中激怒是关键,并映射到页码列表.这基本上在外部for循环中读取,其中key是关键字,value是该关键字出现的页面列表.
编辑2:
dic = collections.defaultdict(list) # declaring the variable dictionary
dic[key].append(value) # inserting the values - useless to tell here
for key in dic:
# Here dic[x] represents list - each value of x
print key,":",dic[x],"\n" #prints the data in dictionary
Run Code Online (Sandbox Code Playgroud)
@ andrea-f对我来说很好,这里是另一个解决方案:
随意挑选两个:)
import json
dic = {
"bomber": [1, 2, 3, 4, 5],
"irritation": [1, 3, 5, 7, 8]
}
filename = "abc.pdf"
json_dict = {}
data = []
for k, v in dic.iteritems():
tmp_dict = {}
tmp_dict["keyword"] = k
tmp_dict["term_freq"] = len(v)
tmp_dict["lists"] = [{"occurrance": i} for i in v]
data.append(tmp_dict)
json_dict["filename"] = filename
json_dict["data"] = data
with open("abc.json", "w") as outfile:
json.dump(json_dict, outfile, indent=4, sort_keys=True)
Run Code Online (Sandbox Code Playgroud)
这是同样的想法,我首先创建一个json_dict
直接在json中保存的大.我使用with
语句来保存json,避免捕获exception
此外,您应该查看文档,了解json.dumps()
您的json
输出是否需要进一步改进.
编辑
只是为了好玩,如果你不喜欢tmp
var,你可以for
在一行中完成所有的数据循环:)
json_dict["data"] = [{"keyword": k, "term_freq": len(v), "lists": [{"occurrance": i} for i in v]} for k, v in dic.iteritems()]
Run Code Online (Sandbox Code Playgroud)
它可以为最终解决方案提供一些不完全可读的东西:
import json
json_dict = {
"filename": "abc.pdf",
"data": [{
"keyword": k,
"term_freq": len(v),
"lists": [{"occurrance": i} for i in v]
} for k, v in dic.iteritems()]
}
with open("abc.json", "w") as outfile:
json.dump(json_dict, outfile, indent=4, sort_keys=True)
Run Code Online (Sandbox Code Playgroud)
编辑2
看起来你不想将你json
的输出保存为所需的输出,但是能够阅读它.
实际上,您也可以使用json.dumps()
以打印您的json.
with open('abc.json', 'r') as handle:
new_json_dict = json.load(handle)
print json.dumps(json_dict, indent=4, sort_keys=True)
Run Code Online (Sandbox Code Playgroud)
还有这里人们问题,但,"filename":
是在列表的末尾印,因为d
的data
到来之前的f
.
要强制执行命令,您必须OrderedDict
在dict的生成中使用.小心语法是丑陋的(imo)python 2.X
这是新的完整解决方案;)
import json
from collections import OrderedDict
dic = {
'bomber': [1, 2, 3, 4, 5],
'irritation': [1, 3, 5, 7, 8]
}
json_dict = OrderedDict([
('filename', 'abc.pdf'),
('data', [ OrderedDict([
('keyword', k),
('term_freq', len(v)),
('lists', [{'occurrance': i} for i in v])
]) for k, v in dic.iteritems()])
])
with open('abc.json', 'w') as outfile:
json.dump(json_dict, outfile)
# Now to read the orderer json file
with open('abc.json', 'r') as handle:
new_json_dict = json.load(handle, object_pairs_hook=OrderedDict)
print json.dumps(json_dict, indent=4)
Run Code Online (Sandbox Code Playgroud)
将输出:
{
"filename": "abc.pdf",
"data": [
{
"keyword": "bomber",
"term_freq": 5,
"lists": [
{
"occurrance": 1
},
{
"occurrance": 2
},
{
"occurrance": 3
},
{
"occurrance": 4
},
{
"occurrance": 5
}
]
},
{
"keyword": "irritation",
"term_freq": 5,
"lists": [
{
"occurrance": 1
},
{
"occurrance": 3
},
{
"occurrance": 5
},
{
"occurrance": 7
},
{
"occurrance": 8
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
但要小心,大多数情况下,最好保存常规 .json
文件以便成为跨语言.