python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python中str与json转换

Python中str与json转换实现过程

作者:zorazhu6

还在为Python解析JSON文件发愁?本文用实例讲解json.load、loads、dump、dumps的区别与用法,帮你轻松掌握JSON数据的读取、写入和转换,避免常见的双引号报错问题

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'>

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文