python中json.loads 返回类型是str 而不是 dict

  

解析本地文件中的Json文件时,json.loads 之后的返回类型是str ,直接上代码

import json

with open ("urlJson.txt",'r',encoding='utf-8') as f:
    data = f.read()
    json_str = json.dumps(data)
    print (type(json_str))
    #print("Python 原始数据:", repr(data))
    #print("JSON 对象:", json_str)

    params_json = json.loads(json_str)
    #print (params_json)
    print (type(params_json))  

运行结果:

<class 'str'>
<class 'str'>

Process finished with exit code 0

  

对此很困惑,看到很奇怪,网上到处都是提示loads 返回的是dict对象。

解决方案:

再loads一次就好了

import json

with open ("urlJson.txt",'r',encoding='utf-8') as f:
    data = f.read()
    json_str = json.dumps(data)
    print (type(json_str))
    #print("Python 原始数据:", repr(data))
    #print("JSON 对象:", json_str)

    params_json = json.loads(json_str)
    #print (params_json)
    print (type(params_json))
    # 再次loads 下
    params_json = json.loads(params_json)
    print (type(params_json))

执行结果:

<class 'str'>
<class 'str'>
<class 'dict'>

Process finished with exit code 0

  

 

参考:

https://bbs.csdn.net/topics/392468521

 

posted @ 2020-08-22 22:49  坑坑kk  阅读(5017)  评论(0编辑  收藏  举报