Update plot with JSON data from POST request

I’m writing an application using flask and AJAX. I am having trouble updating my plot with new data from a POST request. The JSON data returned from my POST request looks good, but I get the following errors when I try to plot it:

Uncaught TypeError: Cannot read property 'style' of undefined
Uncaught TypeError: Cannot read property 'xy' of undefined

When I first render my page the graph works fine.

run.py, main():

...
graphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder)
return render_template('home.html', graphJSON=graphJSON)
....

home.html:

...
var graph = {{graphJSON | safe}};
console.log(graph)
Plotly.newPlot("graph-0", graph.data, graph.layout);
...

However, when I try to update the plot using data recived from a POST request I get errors.

run.py, updatePlot():

...
graphJSON = json.dumps(graph, cls=plotly.utils.PlotlyJSONEncoder)
return graphJSON
...

home.html:

...
  $.post('/updatePlot',
    function(response) {
      console.log(response)
      Plotly.newPlot("graph-0", response.data, response.layout);
    })
  }
...

I also noticed that the console displays the JSON data from the first request as a nested tree diagram, but the data from the POST request as raw text.

Could someone point me to an example? I can’t seem to find what I am looking for. Thank you!

Found the solution: the JSON data needs to be parsed before it can be plotted.

...
$.post('/updatePlot',
    function(response) {
    var figure = JSON.parse(response);        //Parse data before plotting
    console.log(figure)
    Plotly.newPlot("graph-0", figure.data, figure.layout);
    })
  }
...