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
What is the difference between json.dumps and json.load?
提问by AnMaree
What is the difference between json.dumps
and json.load
?
json.dumps
和 和有json.load
什么区别?
From my understanding, one loads JSON into a dictionary and another loads into objects.
根据我的理解,一个将 JSON 加载到字典中,另一个加载到对象中。
采纳答案by chepner
dumps
takes an object and produces a string:
dumps
接受一个对象并产生一个字符串:
>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'
load
would 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 dump
and load
convert between files and objects, while dumps
and loads
convert between stringsand objects. You can think of the s
-less functions as wrappers around the s
functions:
注意dump
andload
在文件和对象之间转换,而dumps
andloads
在字符串和对象之间转换。您可以将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
加载和转储 -> 读取/写入文件而不是字符串