json.load()和json.loads()函数有什么区别

时间:2016-09-27 08:24:26

标签: python json python-2.7

在Python中,json.load()json.loads()之间有什么区别?

我想 load()函数必须与文件对象一起使用(我需要使用上下文管理器),而 loads()函数则需要作为字符串的文件的路径。这有点令人困惑。

json.loads()中的字母“ s ”是否代表字符串

非常感谢您的回答!

6 个答案:

答案 0 :(得分:92)

是的,s代表字符串。 json.loads函数不接受文件路径,但将文件内容作为字符串。查看https://docs.python.org/2/library/json.html上的文档!

答案 1 :(得分:24)

文档很清楚: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]]]]]]]])
  

反序列化fp(.read() - 支持包含文件的文件对象   JSON文档)使用此转换表的Python对象。

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])
  

反序列化s(包含JSON文档的str或unicode实例)   使用此转换表的Python对象。

所以load用于文件,loads用于string

答案 2 :(得分:13)

只需在每个人的解释中添加一个简单的例子,

json.load()

json.load可以反序列化文件本身,即它接受file对象,

with open("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'}}

因为content的类型为file,即<type 'file'>

如果我改用json.loads

with open("json_data.json", "r") as content:
  print(json.loads(content))

我会收到此错误:

  

TypeError:预期的字符串或缓冲区

json.loads()

json.loads()对字符串进行反序列化。

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()的类型是字符串,即<type 'str'>

如果我将json.load()content.read()一起使用,则会收到错误消息,

with open("json_data.json", "r") as content:
  print(json.load(content.read()))

礼物

  

AttributeError:'str'对象没有属性'read'

因此,现在您知道json.load反序列化文件和json.loads反序列化字符串了。

另一个例子

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

如果我想使用json.loads(),我会改用print(json.loads(sys.stdin.read()))

答案 3 :(得分:2)

快速解答(非常简单!)

  

json.load()需要一个文件

     

json.load()需要一个文件(文件对象)-例如您在通过'files/example.json'之类的文件路径指定之前打开的文件。


  

json.loads()需要一个STRING

     

json.loads()需要一个(有效)JSON字符串-即{"foo": "bar"}


示例

  

假设您有一个文件 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'

答案 4 :(得分:1)

json.load()方法(“ load”中没有“ s”)可以直接读取文件:

import json
with open('strings.json') as f:
    d = json.load(f)
    print(d)

json.loads()方法,该方法仅用于 string 自变量。

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

在这里,我们可以看到在使用loads()之后以 string (type(str))作为输入并返回 dictionary

答案 5 :(得分:0)

在python3.7.7中,根据cpython source code,json.load的定义如下:

X[j]

json.load实际上会调用json.loads并使用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) 作为第一个参数。

因此,如果您的代码是:

fp.read()

操作相同:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

但是,如果您需要指定从文件中读取的字节,例如with open (file) as fp: json.load(fp) ,或者要反序列化的字符串/字节不是从文件中读取,则应该使用json.loads()

对于json.loads(),它不仅反序列化字符串,而且还反序列化字节。如果fp.read(10)是字节或字节数组,它将首先被解码为字符串。您也可以在源代码中找到它。

s