python - 如何把字符串轉(zhuǎn)換為字典?
問題描述
保存數(shù)據(jù)時(shí),格式成為此種模式,這樣的數(shù)據(jù)還有很多:
{'status': '0', 'msg': 'ok', 'result': {'name': '露水', 'content': '<p>釋名在秋露重的時(shí)候,早晨去花草間收取。</p><p>氣味甘、平、無毒。</p><p>主治用以煎煮潤肺殺蟲的藥劑,或把治療疥癬、蟲癩的散劑調(diào)成外敷藥,可以增強(qiáng)療效。白花露:止消渴。百花露:能令皮膚健好。柏葉露、菖蒲露:每天早晨洗眼睛,能增強(qiáng)視力。韭葉露:治白癜風(fēng)。每天早晨涂患處。</p>', 'commentary': '', 'translation': '', 'appreciation': '', 'interpretation': ''}}{'status': '0', 'msg': 'ok', 'result': {'name': '明水', 'content': '<p>釋名亦稱方諸水。方諸是一種大蚌的名字。月明之夜,捕得方諸,取其殼中貯水,清明純潔,即是方諸水。</p><p>氣味甘、寒、無毒。</p><p>主治用以洗眼,可以去霧明目,飲此水,還有安神的作用,亦去小兒煩熱。</p>', 'commentary': '', 'translation': ''}}
type后顯示它的格式為字符串,我用了內(nèi)置函數(shù),還是沒能轉(zhuǎn)換為標(biāo)準(zhǔn)的字典格式,如下:
from pprint import pprintimport jsonimport requests
with open(’bencao_detail’,’r’,encoding=’utf8’) as file: str_file = file.read()
str_file
輸出結(jié)果如下:
’{'status': '0', 'msg': 'ok', 'result': {'name': '露水', 'content': '<p>釋名在秋露重的時(shí)候,早晨去花草間收取。</p><p>氣味甘、平、無毒。</p><p>主治用以煎煮潤肺殺蟲的藥劑,或把治療疥癬、蟲癩的散劑調(diào)成外敷藥,可以增強(qiáng)療效。白花露:止消渴。百花露:能令皮膚健好。柏葉露、菖蒲露:每天早晨洗眼睛,能增強(qiáng)視力。韭葉露:治白癜風(fēng)。每天早晨涂患處。</p>', 'commentary': '', 'translation': '', 'appreciation': '', 'interpretation': ''}}n{'status': '0', 'msg': 'ok', 'result': {'name': '明水', 'content': '<p>釋名亦稱方諸水。方諸是一種大蚌的名字。月明之夜,捕得方諸,取其殼中貯水,清明純潔,即是方諸水。</p><p>氣味甘、寒、無毒。</p><p>主治用以洗眼,可以去霧明目,飲此水,還有安神的作用,亦去小兒煩熱。</p>', 'commentary': '', 'translation': ''}}n{'status': '0', 'msg': 'ok', 'result': {'name': '冬霜', 'content': '<p>釋名取霜法:用雞毛掃取,裝入瓶中,密封保存于陰涼處,雖成水液,歷 </p><p>氣味甘、寒、無毒。</p><p>主治飲冬霜可解酒熱,凡酒后面熱耳赤者,飲之立消。傷寒鼻塞,飲冬霜亦可通鼻。 </p><p>附方暑天長痱子及腋下紅腫,用冬霜和蚌粉涂敷,有效。寒熱瘧疾,可秋后霜或冬霜一崐錢半,熱酒送下,亦見效。 </p>', 'commentary': '', 'translation': ''}}n
怎樣可以使它成為一個(gè)一個(gè)的字典?
問題解答
回答1:其實(shí)這種標(biāo)準(zhǔn)字典格式的,eval是最簡單的。
t=’’’{'status': '0', 'msg': 'ok', 'result': {'name': '露水', 'content': '<p>釋名在秋露重的時(shí)候,早晨去花草間收取。</p><p>氣味甘、平、無毒。</p><p>主治用以煎煮潤肺殺蟲的藥劑,或把治療疥癬、蟲癩的散劑調(diào)成外敷藥,可以增強(qiáng)療效。白花露:止消渴。百花露:能令皮膚健好。柏葉露、菖蒲露:每天早晨洗眼睛,能增強(qiáng)視力。韭葉露:治白癜風(fēng)。每天早晨涂患處。</p>', 'commentary': '', 'translation': '', 'appreciation': '', 'interpretation': ''}}’’’a=eval(t)回答2:
你都知道import json了,問什么還來提問
import jsonwith open(’bencao_detail’,’r’,encoding=’utf8’) as file: str_file = file.read() dict_data = json.loads(str_file)// 或者dict_data = json.load(file)
相關(guān)文章:
1. docker不顯示端口映射呢?2. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””3. angular.js - 關(guān)于$apply()4. macos - mac下docker如何設(shè)置代理5. MySQL數(shù)據(jù)庫中文亂碼的原因6. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?7. docker-compose 為何找不到配置文件?8. docker gitlab 如何git clone?9. mysql - 新浪微博中的關(guān)注功能是如何設(shè)計(jì)表結(jié)構(gòu)的?10. css - C#與java開發(fā)Windows程序哪個(gè)好?
