Python json.load() 和 json.loads() 函数有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39719689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between json.load() and json.loads() functions
提问by MMF
In Python, what is the difference between json.load()
and json.loads()
?
在 Python 中,json.load()
和之间有什么区别json.loads()
?
I guess that the load()function must be used with a file object (I need thus to use a context manager) while the loads()function take the path to the file as a string. It is a bit confusing.
我猜load()函数必须与文件对象一起使用(因此我需要使用上下文管理器),而load()函数将文件的路径作为字符串。这有点令人困惑。
Does the letter "s" in json.loads()
stand for string?
字母“ s”json.loads()
代表字符串吗?
Thanks a lot for your answers!
非常感谢你的回答!
采纳答案by Gijs
Yes, s
stands for string. The json.loads
function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!
是的,s
代表字符串。该json.loads
函数不接受文件路径,而是将文件内容作为字符串。查看https://docs.python.org/2/library/json.html上的文档!
回答by Sufiyan Ghori
Just going to add a simple example to what everyone has explained,
只是要在每个人都解释过的内容中添加一个简单的示例,
json.load()
json.load()
json.load
can deserialize a file itself i.e. it accepts a file
object, for example,
json.load
可以反序列化文件本身,即它接受一个file
对象,例如,
# 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))
will output,
将输出,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
If I use json.loads
to open a file instead,
如果我json.loads
用来打开一个文件,
# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
print(json.loads(content))
I would get this error:
我会得到这个错误:
TypeError: expected string or buffer
类型错误:预期的字符串或缓冲区
json.loads()
json.loads()
json.loads()
deserialize string.
json.loads()
反序列化字符串。
So in order to use json.loads
I will have to pass the content of the file using read()
function, for example,
因此,为了使用,json.loads
我必须使用read()
函数传递文件的内容,例如,
using content.read()
with json.loads()
return content of the file,
content.read()
与json.loads()
文件的返回内容一起使用,
with open("json_data.json", "r") as content:
print(json.loads(content.read()))
Output,
输出,
{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}
That's because type of content.read()
is string, i.e. <type 'str'>
那是因为类型content.read()
是字符串,即<type 'str'>
If I use json.load()
with content.read()
, I will get error,
如果我使用json.load()
with content.read()
,我会得到错误,
with open("json_data.json", "r") as content:
print(json.load(content.read()))
Gives,
给,
AttributeError: 'str' object has no attribute 'read'
AttributeError: 'str' 对象没有属性 'read'
So, now you know json.load
deserialze file and json.loads
deserialize a string.
所以,现在你知道了json.load
反序列化文件和json.loads
反序列化一个字符串。
Another example,
另一个例子,
sys.stdin
return file
object, so if i do print(json.load(sys.stdin))
, I will get actual json data,
sys.stdin
返回file
对象,所以如果我这样做print(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'}}
If I want to use json.loads()
, I would do print(json.loads(sys.stdin.read()))
instead.
如果我想使用json.loads()
,我会这样做print(json.loads(sys.stdin.read()))
。
回答by RvdK
Documentation is quite clear: https://docs.python.org/2/library/json.html
文档很清楚:https: //docs.python.org/2/library/json.html
json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
使用此转换表将 fp(包含 JSON 文档的支持 .read() 的类文件对象)反序列化为 Python 对象。
json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.
使用此转换表将 s(包含 JSON 文档的 str 或 unicode 实例)反序列化为 Python 对象。
So load
is for a file, loads
for a string
load
对于一个文件也是如此,loads
对于一个string
回答by Wlad
QUICK ANSWER (very simplified!)
快速回答(非常简化!)
json.load() takes a FILE
json.load() expects a file (file object) - e.g. a file you opened before given by filepath like
'files/example.json'
.
json.load() 需要一个FILE
json.load() 需要一个文件(文件对象)——例如一个你之前打开的文件,如
'files/example.json'
.
json.loads() takes a STRING
json.loads() expects a (valid) JSON string - i.e.
{"foo": "bar"}
json.loads() 需要一个字符串
json.loads() 需要一个(有效的)JSON 字符串 - 即
{"foo": "bar"}
EXAMPLES
例子
Assuming you have a file example.jsonwith this content: { "key_1": 1, "key_2": "foo", "Key_3": null }
假设您有一个包含以下内容的文件example.json:{ "key_1": 1, "key_2": "foo", "Key_3": null }
>>> import json
>>> file = open("example.json")
>>> type(file)
<class '_io.TextIOWrapper'>
>>> file
<_io.TextIOWrapper name='example.json' mode='r' encoding='UTF-8'>
>>> json.load(file)
{'key_1': 1, 'key_2': 'foo', 'Key_3': None}
>>> json.loads(file)
Traceback (most recent call last):
File "/usr/local/python/Versions/3.7/lib/python3.7/json/__init__.py", line 341, in loads
TypeError: the JSON object must be str, bytes or bytearray, not TextIOWrapper
>>> string = '{"foo": "bar"}'
>>> type(string)
<class 'str'>
>>> string
'{"foo": "bar"}'
>>> json.loads(string)
{'foo': 'bar'}
>>> json.load(string)
Traceback (most recent call last):
File "/usr/local/python/Versions/3.7/lib/python3.7/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
回答by Aditya patil
The json.load()method (without "s" in "load") can read a file directly:
所述json.load()方法(无“S”中的“负荷”)可直接读取的文件:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
json.loads()method, which is used for stringarguments only.
json.loads()方法,仅用于字符串参数。
import json
person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>
person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}
print(type(person_dict))
# Output : <type 'dict'>
Here , we can see after using loads() takes a string( type(str) ) as a input and return dictionary.
在这里,我们可以看到使用 load() 后将字符串( type(str) )作为输入并返回字典。
回答by Wenyi Li
In python3.7.7, the definition of json.load is as below according to cpython source code:
在python3.7.7中,根据cpython源码,json.load的定义如下:
def load(fp, *, cls=None, object_hook=None, parse_float=None,
parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
return loads(fp.read(),
cls=cls, object_hook=object_hook,
parse_float=parse_float, parse_int=parse_int,
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
json.load actually calls json.loads and use fp.read()
as the first argument.
json.load 实际上调用 json.loads 并fp.read()
用作第一个参数。
So if your code is:
所以如果你的代码是:
with open (file) as fp:
s = fp.read()
json.loads(s)
It's the same to do this:
这样做是一样的:
with open (file) as fp:
json.load(fp)
But if you need to specify the bytes reading from the file as like fp.read(10)
or the string/bytes you want to deserialize is not from file, you should use json.loads()
但是如果你需要指定从文件中读取的字节,fp.read(10)
或者你想要反序列化的字符串/字节不是来自文件,你应该使用 json.loads()
As for json.loads(), it not only deserialize string but also bytes. If s
is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.
至于 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')