[Django]-"Invalid JSON string" in Google visualization API example

3đź‘Ť

âś…

Unfortunately I can’t comment so this isn’t exactly a full answer, but could you try eval’ing the JSON before trying to use it for the chart?

var json_table = new google.visualization.Table(document.getElementById('dataview'));
var evalledData = eval("("+data+")");
var json_data = new google.visualization.DataTable(evalledData, 0.6);
json_table.draw(json_data, {showRowNumber: true});

I think that may have solved this problem for me in the past; it may not be the safest way to go about it, but you could at least try it for testing.

Alternatively, perhaps play with simplejson to dump your json string from the python instead of just returning the gviz string?

👤oli

5đź‘Ť

Make sure you put 'unsafe-eval' for script sources in Content-Security-Policy.

A policy I use for Google Maps and Google Charts:

<meta
  http-equiv="Content-Security-Policy"
  content="
    default-src 'self';
    script-src 'self' 'unsafe-inline' 'unsafe-eval' maps.googleapis.com www.google.com www.google-analytics.com;
    img-src 'self' csi.gstatic.com www.google-analytics.com maps.gstatic.com maps.googleapis.com;
    style-src 'self' 'unsafe-inline' www.google.com fonts.googleapis.com ajax.googleapis.com;
    font-src 'self' fonts.gstatic.com;
  "
/>
👤nhereveri

2đź‘Ť

JSON parsers should require field names to be delimited by double quotes, as outlined in the specification JSON RFC 4627:

An object is an unordered collection
of zero or more name/value pairs,
where a name is a string […] A string begins and ends with quotation marks.

So, the JSON should be formatted like this:

{
    "cols": [
        {
            "id": "sensor",
            "label": "Sensor name",
            "type": "string" 
        },
        {
            "id": "timestamp",
            "label": "Time",
            "type": "string" 
        },
        {
            "id": "value",
            "label": "Sensor value",
            "type": "string" 
        } 
    ],
    "rows": [
        {
            "c": [
                {
                    "v": "testsensor" 
                },
                {
                    "v": "2011-05-09 16: 06: 43.936000" 
                },
                {
                    "v": "22.0" 
                } 
            ] 
        },
        {
            "c": [
                {
                    "v": "testsensor" 
                },
                {
                    "v": "2011-05-09 16: 56: 23.367000" 
                },
                {
                    "v": "23.0" 
                } 
            ] 
        } 
    ]
}
👤Chris Fulstow

0đź‘Ť

Had the same issue, even when stripping the options to an empty dictionary (resulting in the error “Invalid JSON string: {}” …). Turns out the issue is with the script-src CSP, documented here: https://github.com/keen/keen-js/issues/394

“Solution” is to add unsafe-eval to the CSP.

👤user1769889

Leave a comment