Xavier Peña
Xavier Peña

Reputation: 7899

get json from API: array is interpreted as a string

I have this answer from an API (written by me):

[[new Date(2017,0,28,16,00,00),[0.201766,0.201766,0.201766],[0.309878,0.309878,0.309878],[0.287467,0.287467,0.287467],[null,null,null], ...

I want my view to interpret this answer as javascript, but it doesn't. It assumes it is a string.

$.getJSON('http://localhost:XXXX/...', function (data) {

    // data.jsAlignedData == [[new Date(2017,0,28,16,00,00),[0.201766,0.201766,0.201766], ...

    console.log(data.jsAlignedData);
    // Shows it as a string

    var test = JSON.parse(data.jsAlignedData);
    // Error: Unexpected token e in JSON at position 3 
    // (IMO it's the 'e' from 'new')

    // it doesn't even reach this point:
    console.log(test);          
}

The final goal is to build a Dygraphs plot with a native array for increased speed (see "native array" in the documentation).

Upvotes: 0

Views: 132

Answers (1)

Aloene
Aloene

Reputation: 326

You have to serialize to date using JSON standard (see https://en.wikipedia.org/wiki/ISO_8601 for example) to be able to parse it using JSON.parse().

Edit: "JSON standard" for date type is inaccurate because you will have to interpret the date string as a JS date once parsed... (as stated in @charlietfl comment)

Upvotes: 1

Related Questions