【问题标题】:Django load local json fileDjango加载本地json文件
【发布时间】:2012-05-16 21:56:41
【问题描述】:

我有一个 ajax 视图:

def ajax_prices(request):
    data = {'data':'data'}
    return HttpResponse(json.dumps(data), mimetype='application/json')

我想使用本地 json 文件 (prices.json) 对此进行测试。如何导入本地 json 文件?

本地 json 文件 'prices.json'

{"aaData": [
[1, "70.1700", "2008-12-29 11:23:00"],
[2, "70.2600", "2008-12-29 16:22:00"],
[3, "70.6500", "2008-12-30 11:30:00"],
[4, "70.8700", "2008-12-30 16:10:00"],
[5, "70.5500", "2009-01-02 11:09:00"],
[6, "70.6400", "2009-01-02 16:15:00"],
[7, "70.6500", "2009-01-05 11:17:00"]
]}

我不能这样做:

data = '/static/prices.json'

【问题讨论】:

    标签: python django json


    【解决方案1】:

    使用 json 模块:

    import json
    
    json_data = open('/static/prices.json')   
    data1 = json.load(json_data) # deserialises it
    data2 = json.dumps(data1) # json formatted string
    
    json_data.close()
    

    请参阅here 了解更多信息。

    正如 Joe 所说,最好使用 fixturesfactories 作为测试数据。

    【讨论】:

    • 我收到一个错误 No such file or directory: '/static/portal/sample-dap.json'... 文件位于 appfolder/static/app/prices.json
    • 路径应该相对于调用脚本,否则指定完整路径
    • 应该是:-> data2 = json.dumps(data) // json 格式字符串
    【解决方案2】:

    这里的技巧是使用python的内置方法open该文件,读取其内容并使用json模块解析它

    import json
    
    data = open('/static/prices.json').read() #opens the json file and saves the raw contents
    jsonData = json.loads(data) #converts to a json structure
    

    【讨论】:

      【解决方案3】:

      您应该为此使用 Django 固定装置。

      https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs

      【讨论】:

        猜你喜欢
        • 2011-11-12
        • 1970-01-01
        • 2012-09-12
        • 2017-05-08
        • 2021-05-31
        • 2012-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多