Skip to main content
 首页 » 编程设计

python之在 python 中获取一个 JSON 对象

2025年05月04日15leader

通常我使用 Bottle 构建的网络服务返回 JSON 文件,这工作正常。但是,我有一个需要调用本地函数的异常。

这是我尝试做的:

import json 
def getData(): 
    return json.dumps({'data': someData }) 
 
def function(): 
    try: 
        # Fail 
    except: 
        print getData() 
        print type(getData()) 
        json.load(getData()) 

所以它打印:

{"data": "myData"} 
<type 'str'> 
[...] 
AttributeError: 'str' object has no attribute 'read' 

所以 json.dumps 给了我一个字符串。如何将其用作 JSON?

请您参考如下方法:

json.load 从文件对象加载 JSON。

json.loads 从字符串加载。这就是您想要的。