Python json.dumps 和 json.load 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32911336/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:28:21  来源:igfitidea点击:

What is the difference between json.dumps and json.load?

pythonjson

提问by AnMaree

What is the difference between json.dumpsand json.load?

json.dumps和 和有json.load什么区别?

From my understanding, one loads JSON into a dictionary and another loads into objects.

根据我的理解,一个将 JSON 加载到字典中,另一个加载到对象中。

采纳答案by chepner

dumpstakes an object and produces a string:

dumps接受一个对象并产生一个字符串:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

loadwould take a file-like object, read the data from that object, and use that string to create an object:

load将获取一个类似文件的对象,从该对象读取数据,并使用该字符串创建一个对象:

with open('file.json') as fh:
    a = json.load(fh)

Note that dumpand loadconvert between files and objects, while dumpsand loadsconvert between stringsand objects. You can think of the s-less functions as wrappers around the sfunctions:

注意dumpandload在文件和对象之间转换,而dumpsandloads字符串和对象之间转换。您可以将s-less 函数视为函数的包装器s

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

回答by stackhelper101

json loads -> returns an object from a string representing a json object.

json 加载 -> 从表示 json 对象的字符串返回一个对象。

json dumps -> returns a string representing a json object from an object.

json dumps -> 从对象返回一个表示 json 对象的字符串。

load and dump -> read/write from/to file instead of string

加载和转储 -> 读取/写入文件而不是字符串