問題が説明されるように、私はネストされたJSONオブジェクトを生成しようとしています。この場合、私はfor
ループのデータを辞書dic
から取得しています。以下のコードです:動的なネストされたJSONオブジェクトと配列の生成 - Python
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("}")
期待出力は次のとおりです。
{
"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
}]
}
しかし、現在、私は以下のような出力を取得しています:
{
"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
}]
}
助けてください、私が解決しようとしてきましたそれは失敗しました。すでに他の回答を確認していて、全く助けてくれなかったので、重複していないようにしてください。
編集1: 入力は基本的に、そのマッピングタイプ、例えば<String, List>
ある辞書dic
から取られる:刺激はキーである「刺激」=> [1,3,5,7,8] 、ページ番号のリストにマップされます。 これは基本的にouter 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
正しく作成された 'json'ファイルの場合は、テキストとしてインポートするのではなく' json'モジュールを使用できます。あなたの入力ファイルの詳細を提供できますか? – asongtoruin
入力が長いプロセスなので、入力の抽象化を使って回答を編集します –
json.dumpを使用して、さらにデータが到着したときにJSONオブジェクトを更新しないのはなぜですか? –