JSON Parse error: Unexpected identifier "undefined"

97
February 08, 2022, at 3:40 PM

i just switched to a mac today and i noticed the JSON.parse that works on other browsers, throws this error on safari.

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

This is the JSON response from my PHP code

   {"dataPointsX": "[\"31 Jan\",\"01 Feb\",\"02 Feb\",\"03 Feb\",\"04 Feb\",\"05 Feb\",\"06 Feb\"]", "dataPointsY": "[\"0\",\"0\",\"7287\",\"24572\",\"30657\",\"27865\",\"0\"]", "dataPoints2Y": "[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]"}

This is my Javascript code

$.get('chartdata.php', async function (res) {
   console.log(res)
   var res = JSON.parse(res);
});

Please help

UPDATE

I have updated my PHP to echo this

{"dataPointsX":["31 Jan","01 Feb","02 Feb","03 Feb","04 Feb","05 Feb","06 Feb"],"dataPointsY":["0","0","7287","24572","30632","27820","0"],"dataPoints2Y":["0","0","0","0","0","0","0"]}

It works on chrome, safari still throwing this error

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

Console.log(JSON.parse(res)) shows this on chrome

dataPoints2Y: (7) ['0', '0', '0', '0', '0', '0', '0']
dataPointsX: (7) ['31 Jan', '01 Feb', '02 Feb', '03 Feb', '04 Feb', '05 Feb', '06 Feb']
dataPointsY: (7) ['0', '0', '7287', '24572', '30489', '27744', '0']
[[Prototype]]: Object
Answer 1

It looks like your PHP code is JSON encoding content that's already JSON encoded, maybe something like this:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => json_encode($points)]);

This yields the oddly quoted string:

{"dataPointsX":"[\"31 Jan\",\"01 Feb\",\"03 Feb\"]"}

You only want to call json_encode() once:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => $points]);
READ ALSO
Set Integers getItemViewType RecyclerView

Set Integers getItemViewType RecyclerView

I have an array list of integers[3,-3,7,9,8,1]

86
Hide "foreach" results if there is only one result

Hide "foreach" results if there is only one result

I have post type with an "email" custom fieldWhen editing a post, I would like to know if other posts have the same email value

85
VSC wrong java dependencies

VSC wrong java dependencies

I have a strange behaviour in Visual Studio Code, trying to debug a simple code with the VSC Debugger I have a runtime error, running the same code with Gradle the code works !

87