简体   繁体   中英

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) . I pass data as context to the html file.

In the HTML file, Using JS I access the JSON object with this code:

{{ 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. Object.fromEntries is not working and I get the error 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. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. 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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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