简体   繁体   English

json.dumps 将对象作为字符串而不是 JSON 对象返回

[英]json.dumps returns the objects as a string instead of a JSON object

In the views.py : data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder) .views.py中: data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder) I pass data as context to the html file.我将data作为上下文传递给 html 文件。

In the HTML file, Using JS I access the JSON object with this code:在 HTML 文件中,使用 JS 我使用以下代码访问 JSON 对象:

{{ data|json_script:"hello-data" }}
<script type="text/javascript">
    var data = JSON.parse(document.getElementById('hello-data').textContent);
    document.getElementById('id_line_one').onchange = function(event){
            console.log(typeof data)
            alert(data);
            document.getElementById('id_line_one_unit_price').value = data[this.value];
};

</script>

I expect the var data to be a dictionary but it seems to be a String.我希望var data是一个字典,但它似乎是一个字符串。 Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>) . Object.fromEntries不起作用,我收到错误Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>) JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. JSON.parse正在删除双引号,我得到[[1, 56000], [2, 55000]]但我无法将其作为字典访问。 Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object.每当我使用索引访问它时,它都会返回单个字符作为输出,而不是将其视为 dict 对象。 How can I convert it into a dictionary?如何将其转换为字典? Thanks谢谢

The problem is that you are obtaining a list from the following line:问题是您正在从以下行获取列表:

data1 = list(Inventory.objects.values_list('product_number','amount'))

Hence, you are just converting a list to JSON and, then, parsing this JSON, which yields a list.因此,您只是将一个列表转换为 JSON,然后解析此 JSON,从而生成一个列表。

Try to use the following instead:尝试改用以下内容:

from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
data_obj_model = Inventory.objects.all()
data1=serializers.serialize('json', data_obj_model, cls=DjangoJSONEncoder)

Then, you can access, in your JavaScript code, all the fields of the model using data["fields"].field_of_interest .然后,您可以在 JavaScript 代码中使用data["fields"].field_of_interest访问模型的所有字段。

Or you can also create a custom dictionary with the two fields you were interested in as follows:或者您也可以使用您感兴趣的两个字段创建一个自定义字典,如下所示:

data1 = dict(Inventory.objects.values_list('product_number','amount'))

This could be used as a dictionary in the JavaScript after parsing it.这可以在解析后用作 JavaScript 中的字典。

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

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