Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python json.load()和json.load()函数之间有什么区别_Python_Json_Python 2.7 - Fatal编程技术网

Python json.load()和json.load()函数之间有什么区别

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对象 反序列

在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
(a
str
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')