json.dumps和json.load有什么区别?[关闭]

问题:json.dumps和json.load有什么区别?[关闭]

json.dumps和之间有什么区别json.load

据我了解,一个将JSON加载到字典中,另一个则加载到对象中。

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

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


回答 0

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

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

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

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

需要注意的是dumpload文件和对象,而之间的转换dumpsloads相互转换的字符串和对象。您可以将s-less函数视为函数的包装器s

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

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

dumps takes an object and produces a string:

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

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 strings and objects. You can think of the s-less functions as wrappers around the s functions:

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

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

回答 1

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

json dumps->从对象返回代表json对象的字符串。

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

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

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

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