Question

I'm trying to return data to javascript using json.dumps in order to show data to the user.

Dajax call when button is pressed: Dajaxice.chamber.ATableUpdate(TableUpdate);

My ajax function:

@dajaxice_register
def ATableUpdate(request):
    mean = [[900, 2.1],[1000, -20.4],[1100, -15.4],[1200, -30.5]]
    numpy.savetxt("table_mean.txt", mean)
    mean2 = numpy.loadtxt("table_mean.txt")
    return json.dumps({"mean": mean})

If I return the value mean as shown, it all works, but if instead I return mean2 (the same values read from a file with numpy) it does not work, and gives the error: "Is not JSON serializable"

The code is simply to pull data from file and show the data to the user in a table. The file is updated with values from sensors connected to the system.

Any ideas on how to serialize my numpy data? Or how to return an array to my html without using javascript and only using djangos template?

HTML class to print table in

<div class="box_result_inner">
<table cellspacing="0px" cellpadding="1px" border="1px" id="tablehtml">
</table>  
</div>

Javascript

function TableUpdate(data){
    var col=data.mean[0].length;
    var row=data.mean.length;
    buffer='';
    for(var r = 0; r < row; r++){
        buffer += "<tr>";
        for(var c = 0; c < col ; c++){
            buffer += "<td>" + data.mean[r][c] + "</td>";
        }
        buffer += "</tr>";
    }
    document.getElementById("tablehtml").innerHTML = buffer;
 }

Update Unfortunately list didn't work for me as it added array in front of every row, however, got it working with:

with open("chamber/control/data/table_mean.txt", 'wb') as fp:
    json.dump(mean, fp)

with open("chamber/control/data/table_mean.txt", 'rb') as fp:
    mean2 = json.load(fp)

return json.dumps({"mean": mean2})
Was it helpful?

Solution

The Python JSON module can only handle certain native Python types listed here.

The numpy.loadtxt function returns an array type and so is not serializable.

Instead, convert the array to a list, then convert to JSON:

mean2 = list(numpy.loadtxt("table_mean.txt"))
return json.dumps({"mean": mean})

This operation may be expensive depending on the size of the numpy array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top