首页  >  问答  >  正文

python - 如何把字符串转换为字典?

保存数据时,格式成为此种模式,这样的数据还有很多:

{"status": "0", "msg": "ok", "result": {"name": "露水", "content": "<p>释名
在秋露重的时候,早晨去花草间收取。</p><p>气味
甘、平、无毒。</p><p>主治
用以煎煮润肺杀虫的药剂,或把治疗疥癣、虫癞的散剂调成外敷药,可以增强疗效。
白花露:止消渴。
百花露:能令皮肤健好。
柏叶露、菖蒲露:每天早晨洗眼睛,能增强视力。
韭叶露:治白癜风。每天早晨涂患处。</p>", "commentary": "", "translation": "", "appreciation": "", "interpretation": ""}}
{"status": "0", "msg": "ok", "result": {"name": "明水", "content": "<p>释名
亦称方诸水。方诸是一种大蚌的名字。月明之夜,捕得方诸,取其壳中贮水,清明纯洁,即是方诸水。</p><p>气味
甘、寒、无毒。</p><p>主治
用以洗眼,可以去雾明目,饮此水,还有安神的作用,亦去小儿烦热。</p>", "commentary": "", "translation": ""}}

type后显示它的格式为字符串,我用了内置函数,还是没能转换为标准的字典格式,如下:

from pprint import pprint
import json
import requests
with open('bencao_detail','r',encoding='utf8') as file:
    str_file = file.read()
str_file

输出结果如下:

'{"status": "0", "msg": "ok", "result": {"name": "露水", "content": "<p>释名
在秋露重的时候,早晨去花草间收取。</p><p>气味
甘、平、无毒。</p><p>主治
用以煎煮润肺杀虫的药剂,或把治疗疥癣、虫癞的散剂调成外敷药,可以增强疗效。
白花露:止消渴。
百花露:能令皮肤健好。
柏叶露、菖蒲露:每天早晨洗眼睛,能增强视力。
韭叶露:治白癜风。每天早晨涂患处。</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

怎样可以使它成为一个一个的字典?

阿神阿神2675 天前805

全部回复(2)我来回复

  • phpcn_u1582

    phpcn_u15822017-06-22 11:54:19

    其实这种标准字典格式的,eval是最简单的。

    t='''{"status": "0", "msg": "ok", "result": {"name": "露水", "content": 
    "<p>释名在秋露重的时候,早晨去花草间收取。</p><p>气味甘、平、无毒。</p><p>主治用以煎煮润肺杀虫的药剂,或把治疗疥癣、虫癞的散剂调成外敷药,可以增强疗效。白花露:止消渴。百花露:能令皮肤健好。柏叶露、菖蒲露:每天早晨洗眼睛,能增强视力。韭叶露:治白癜风。每天早晨涂患处。</p>", "commentary": "", "translation": "", "appreciation": "", "interpretation": ""}}'''
    
    a=eval(t)
    

    回复
    0
  • 巴扎黑

    巴扎黑2017-06-22 11:54:19

    你都知道import json了,问什么还来提问

    import json
    
    with open('bencao_detail','r',encoding='utf8') as file:
        str_file = file.read()
        dict_data = json.loads(str_file)
        
        // 或者
        
        dict_data = json.load(file)
        

    回复
    0
  • 取消回复