当前位置: 代码网 > it编程>前端脚本>Python > Python中str与json转换实现过程

Python中str与json转换实现过程

2026年09月06日 Python 我要评论
json.load()将一个json格式的文件对象转化为python对象(dict)(文件名可以不是xxx.json, 但是文件内容一定是json格式)解析文件时常用,解析后type是<clas

json.load()

将一个json格式的文件对象转化为python对象(dict)

(文件名可以不是xxx.json, 但是文件内容一定是json格式)

解析文件时常用,解析后type是<class 'dict'>

json.load(fp, *, cls=无, object_hook=无, parse_float=无, parse_int=无, parse_constant=无, object_pairs_hook=无, **kw)
deserialize fp (a .read()-supporting text file or binary file containing a json document) to a python object using this conversion table.

将 fp(支持文本文件或包含 json 文档的二进制文件)反序列化为 python 对象

with open('aa.json', 'r') as data_file:
    f=json.load(data_file)
print(type(f))
print(f)

>>> <class 'dict'>
>>> {'today': '0326', 'id': '11'}
import json
file= open('aa.json')
data = json.load(file)
file.close()

效果一样,但是用with打开文件更好,会自动调用close()关闭文件

如果文件内容不是json格式,会报错:

raise jsondecodeerror("expecting value", s, err.value) from none
json.decoder.jsondecodeerror: expecting value: line 2 column 1 (char 1)

json.loads()

将一个json对象(type:str)

转化为相对应的python对象(dict),loads不能解析文件,会报错

常用于将str类型的数据转成dict。

json.loads(s, *, cls=无, object_hook=无, parse_float=无, parse_int=无, parse_constant=无, object_pairs_hook=无, **kw)
deserialize s (a str, bytes or bytearray instance containing a json document) to a python object using this conversion table.

使用此转换表将 s(包含 json 文档的实例)反序列化为 python 对象。

a= "{'today': '0326', 'id': '11'}"
b = json.loads(a)
print(b)

报错

json.decoder.jsondecodeerror: expecting property name enclosed in double quotes: line 1 column 2 (char 1)

解决方案:字符串单引号引用,里面数据用双引号

a= '{"today": "0326", "id": "11"}'

其他方式后续补充

loads解析文件报错

raise typeerror(f'the json object must be str, bytes or bytearray, '

typeerror: the json object must be str, bytes or bytearray, not textiowrapper

json.dump()

数据可写入到文件中, 无返回数据

json.dump(obj, fp, *, skipkeys=false, ensure_ascii=true, check_circular=true, allow_nan=true, cls=none, indent=none, separators=none, default=none, sort_keys=false, **kw)
serialize obj as a json formatted stream to fp (a -supporting file-like object) using this conversion table..write()

使用此转换表将 obj 作为 json 格式的流序列化为 fp(支持类似文件的对象)。.write()

a= {"today": "0326", "id": "22222"}
with open("bb.json",'w') as f:
    json.dump(a, f)

输出:

print(type(json.dump(a, f)))

<class 'nonetype'>

数据a写入到aa.json文件里

json.dumps()

将python的对象转化为对应的json对象(str)

json.dumps(obj, *, skipkeys=false, ensure_ascii=true, check_circular=true, allow_nan=true, cls=none, indent=none, separators=none, default=none, sort_keys=false, **kw)

将 obj 序列化为json对象(using str)。这些参数的含义与dump中的含义相同。

note keys in key/value pairs of json are always of the type str. when a dictionary is converted into json, all the keys of the dictionary are coerced to strings. as a result of this, if a dictionary is converted into json and then back into a dictionary, the dictionary may not equal the original one. that is, loads(dumps(x)) != x if x has non-string keys.

注意:

json 的键/值对中的键始终为 类型。

什么时候 一个字典转换成json,字典的所有键都是 被胁迫到字符串。因此,如果字典被转换 进入json,然后返回到字典中,字典可能不等于 原来的那个。

也就是说,loads(dumps(x)) != x if x has non-string keys.

a= {"today": "0326", "id": "22222"}
#a= [{"today": "0326", "id": "22222"}]
with open("bb.json",'w') as f:
    print(json.dump(a, f))
    print(type(json.dump(a, f)))
    json.dump(a, f)

print(json.dumps(a))
print(type(json.dumps(a)))

>>>
none
<class 'nonetype'>
{"today": "0326", "id": "22222"}
<class 'str'>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com