日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python生成json_生成动态嵌套JSON对象和数组-python - python

發(fā)布時間:2023/12/10 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python生成json_生成动态嵌套JSON对象和数组-python - python 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

正如問題所解釋的那樣,我一直在嘗試生成嵌套的JSON對象。在這種情況下,我有for循環(huán)從字典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("}")

預期輸出為:

{

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

輸入基本上是從映射類型為dic的字典中獲取的

例如:“刺激” => [1、3、5、7、8]

其中刺激是關鍵,并映射到頁碼列表。

這基本上是在外部for循環(huán)中讀取的,其中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

參考方案

@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)

同樣的想法,我首先創(chuàng)建一個大的json_dict以直接保存在json中。我使用with語句保存json以避免捕獲exception

另外,如果將來需要改進json.dumps()輸出,則應該查看json的文檔。

編輯

而且只是為了好玩,如果您不喜歡tmp var,則可以單行處理所有數據for循環(huán):)

json_dict["data"] = [{"keyword": k, "term_freq": len(v), "lists": [{"occurrance": i} for i in v]} for k, v in dic.iteritems()]

它可以為最終解決方案提供一些不完全可讀的內容,例如:

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)

編輯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)

但是,這里仍然存在一個問題,因為列表中"filename":的d在data之前,所以f會打印在列表的末尾。

要強制命令,您將必須在字典的生成中使用OrderedDict。請注意,python 2.X的語法很丑(imo)

這是新的完整解決方案;)

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)

將輸出:

{

"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

}

]

}

]

}

但是要小心,在大多數情況下,最好保存常規(guī)的.json文件以使它們成為跨語言的。

Python uuid4,如何限制唯一字符的長度 - python

在Python中,我正在使用uuid4()方法創(chuàng)建唯一的字符集。但是我找不到將其限制為10或8個字符的方法。有什么辦法嗎?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc謝謝。 參考方案 嘗試:x = uuid4() str(x)[:8] 輸出:"ffc69c1b" Is there a way to…json.dumps弄亂順序 - python

我正在使用json module創(chuàng)建一個包含類似條目的json文件json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "cou…JSON SCHEMA PATTERN逗號分隔列表 - python

我的json模式中具有以下模式,并且我需要根據以下模式包含逗號分隔的值。當前模式只能像DV2一樣處理一種模式所以我應該如何修改我的模式以包括多個字符串,如下所示,但它應該與聲明的模式匹配。例如:“ DV2”,“ DEV1”,“ DEV3”,“ ST”, "ENVIRONMENT": { "type": "st…Python中的Json操作 - python

Latest_json和Historic_json函數返回:return(frame.to_json(orient='records')) 主功能:recentdata = recent_json(station) historicdata = historic_json(station) alldata = historicdata +…Python-crontab模塊 - python

我正在嘗試在Linux OS(CentOS 7)上使用Python-crontab模塊我的配置文件如下:{ "ossConfigurationData": { "work1": [ { "cronInterval": "0 0 0 1 1 ?", "attribute&…

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的python生成json_生成动态嵌套JSON对象和数组-python - python的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。