Python json.load()和json.load()函数之间有什么区别
在Python中,Python json.load()和json.load()函数之间有什么区别,python,json,python-2.7,Python,Json,Python 2.7,在Python中,json.load()和json.load()之间有什么区别 我猜load()函数必须与file对象一起使用(因此我需要使用上下文管理器),而load()函数将文件路径作为字符串。这有点令人困惑 json.loads()中的字母“s”代表字符串吗 非常感谢你的回答 是,s代表字符串。json.loads函数不采用文件路径,而是将文件内容作为字符串。请查看上的文档 文档非常清楚: 反序列化fp(a.read()-支持包含 JSON文档)转换为使用此转换表的Python对象 反序列
json.load()
和json.load()
之间有什么区别
我猜load()函数必须与file对象一起使用(因此我需要使用上下文管理器),而load()函数将文件路径作为字符串。这有点令人困惑
json.loads()
中的字母“s”代表字符串吗
非常感谢你的回答 是,
s
代表字符串。json.loads
函数不采用文件路径,而是将文件内容作为字符串。请查看上的文档 文档非常清楚:
反序列化fp(a.read()-支持包含
JSON文档)转换为使用此转换表的Python对象
反序列化s(包含JSON文档的str或unicode实例)
使用此转换表创建Python对象
因此,
load
是一个文件,load
是一个字符串
只是给大家解释的内容添加一个简单的例子
json.load()
json.load
可以反序列化文件本身,例如,它接受文件
对象
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
将输出
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
如果我使用json.loads
打开一个文件
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
我会得到这个错误:
TypeError:应为字符串或缓冲区
json.loads()
json.loads()
反序列化字符串
因此,为了使用json.loads
,我必须使用read()
函数传递文件的内容,例如
# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
print(json.load(content))
使用content.read()
和json.loads()
返回文件的内容
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
输出,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
这是因为content.read()
的类型是字符串,即
如果我将json.load()
与content.read()
一起使用,我将得到错误
with open("json_data.json", "r") as content:
print(json.load(content.read()))
给
AttributeError:“str”对象没有属性“read”
现在,您知道了json.load
反序列化文件和json.load
反序列化字符串
另一个例子,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
sys.stdin
返回文件
对象,因此如果我执行打印(json.load(sys.stdin))
,我将获得实际的json数据
cat json_data.json | ./test.py
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
如果我想使用json.loads()
,我会改为使用print(json.loads(sys.stdin.read())
。快速回答(非常简单!)
load()接受一个文件
json.load()需要一个文件(文件对象)——例如,您以前打开的文件,由文件路径提供,如'files/example.json'
loads()接受一个字符串 loads()需要一个(有效的)json字符串,即
{“foo”:“bar”}
例子 假设您有一个文件example.json包含以下内容:{“key_1”:1,“key_2”:“foo”,“key_3”:null} 导入json >>>file=open(“example.json”) >>>类型(文件) >>>文件 >>>加载(文件) {'key_1':1,'key_2':'foo','key_3':无} >>>加载(文件) 回溯(最近一次呼叫最后一次): 文件“/usr/local/python/Versions/3.7/lib/python3.7/json/_init__.py”,第341行,在loads中 TypeError:JSON对象必须是str、bytes或bytearray,而不是TextIOWrapper >>>字符串='{“foo”:“bar”}' >>>类型(字符串) >>>串 “{”foo:“bar”}” >>>加载(字符串) {'foo':'bar'} >>>加载(字符串) 回溯(最近一次呼叫最后一次): 文件“/usr/local/python/Versions/3.7/lib/python3.7/json/_init__.py”,第293行,已加载 返回加载(fp.read(), AttributeError:“str”对象没有属性“read”
在python3.7.7中,json.load的定义如下: json.load实际上调用json.load并使用
fp.read()
作为第一个参数
因此,如果您的代码是:
with open (file) as fp:
s = fp.read()
json.loads(s)
这样做也是一样的:
with open (file) as fp:
json.load(fp)
但是,如果需要将从文件读取的字节指定为fp.read(10)
,或者要反序列化的字符串/字节不是从文件读取的,则应该使用json.loads()
至于json.loads(),它不仅反序列化字符串,还反序列化字节。如果s
是bytes或bytearray,它将首先被解码为字符串。您也可以在源代码中找到它
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
...
"""
if isinstance(s, str):
if s.startswith('\ufeff'):
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')
json.loads(s,*)
-反序列化s
(astr
,bytes
或bytearray
包含json文档的实例)-链接的文章指向错误的python版本。问题标记为2.7。“类文件对象”与“str/unicode实例”。我不明白还有什么不清楚?关于json.dump
/dumps
&json.load
/load
仅供参考,在Python 3.6.5中,with open()
和json.loads()
返回一个异常:类型错误:json对象必须是str、bytes或bytearray,而不是“TextIOWrapper”
def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
"""Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.
...
"""
if isinstance(s, str):
if s.startswith('\ufeff'):
raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
s, 0)
else:
if not isinstance(s, (bytes, bytearray)):
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
f'not {s.__class__.__name__}')
s = s.decode(detect_encoding(s), 'surrogatepass')