繁体   English   中英

在Django中与熊猫奋斗到JSON

[英]Struggling with Pandas to JSON in Django

我有以下在django视图中创建的pandas数据框:

Date        Actual ticks
26-Sep-14   20
29-Sep-14   40
15-Oct-14   -10
20-Oct-14   5

使用pandas从csv文件读取数据,然后将其更改为json对象,然后发送至django模板:

df = pd.read_csv('article/DailyStats.csv', usecols=['Date', 'Actual ticks'])
df.to_json()
return render_to_response('article/test.html', {'df': df})

现在是我遇到问题的地方,当我尝试在模板中使用JSON对象时:

<script type="text/javascript">
    $.getJSON({{ df }}, function(data){
        //do something
    })
 </script>

在我的Chrome浏览器控制台中,出现错误:Uncaught SyntaxError:意外的标识符

如果在浏览器中查看“源”,则会看到以下内容:

    <script type="text/javascript">
        $.getJSON(           Actual ticks
        Date                   
        26-Sep-14            20
        29-Sep-14            40
        15-Oct-14            -10
        20-Oct-14            5, function(data){
        })
    </script>

我想要的只是一个带有键(即日期)和值(即“实际报价”)列表的JSON。 我想这与列标题弄乱了有关。

最终,我希望能够遍历json以显示日期和相应的值,但是直到该错误不再发生之前,我才能这样做。

非常感谢您的任何建议。

更新:感谢@Anzel指出我没有将JSON对象分配给变量。 我现在已经做到了,即:df_json = df.to_json()

但产生的json无效:

[
    [
        &quot;26-Sep-14&quot;,
        20
    ],
    [
        &quot;29-Sep-14&quot;,
        40
    ],
    [
        &quot;15-Oct-14&quot;,
        -10
    ],
    [
        &quot;20-Oct-14&quot;,
        5
    ]
]

知道如何获取它以创建有效的JSON吗?

至于第二个问题,Django正在对字符串进行转义,以便可以安全地在HTML中使用(不能包含额外的HTML或JavaScript位)。

要告诉Django不要这样做,请使用safe模板过滤器。

另外,由于这需要成为JavaScript中的字符串文字,因此您需要在其周围加上引号:

var json_data = JSON.parse("{{ df_json|safe }}");

问题是,您没有将json对象传递给render_to_response ,仅将df作为DataFrame传递了。

# this line, you're calling to_json, but haven't assigned to df itself
df.to_json()

# assign it to df_json (or df if you want), and pass it again to render_to_response
df_json = df.to_json()
return render_to_response('article/test.html', {'df': df_json})

在您的模板中,由于您已经传递了json对象,因此无需执行任何ajax调用,只需解析json就可以了,就像这样(尚未经过测试,但应该可以正常工作) ,现在用|safe 更新 ,并用@RemcoGerlich指出的引号引起来:

<script type="text/javascript">
    var json_data = JSON.parse("{{ df_json|safe }}"); // df if you assign df as the json
    // do whatever you want with json_data as usual
 </script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM