Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data [closed]

Tags:

json

ajax

php

when i use....

 var jsonData = JSON.parse(xhttp.responseText);

i get an error => "JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data"

this is my JSON data from a php script

{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}

Can some please help?.... Thanks

like image 778
Dabiko Blaise Avatar asked Dec 05 '25 18:12

Dabiko Blaise


2 Answers

I have had the same problem for the past several years. Sometimes the problem is not related to invalid JSON .. like me now.. the problem is that I must use stringify before JSON.parse

var db = JSON.stringify(data);
var db = JSON.parse(db);

And sometimes in php you must use json_encode($data) correctly.

And sometimes your JSON is not valid ( Online JSON Validator )

like image 65
Mostafa Avatar answered Dec 08 '25 06:12

Mostafa


A little bit late to the party, but @igniz87 and @Benjamin James Kippax's answers open your website to security issues, and it is so dangerous to follow their example. As Owasp reads,

ALWAYS RETURN JSON WITH AN OBJECT ON THE OUTSIDE

Hence, so as to be a layer protected from the barbarism of hackers, you need to ALWAYS have the outside primitive be an object for JSON strings. As you can clearly see, the mentioned people's answers do not follow this crucial security rule.

Owasp, moreover, brings an example and says that a JSON like the following is EXPLOITABLE:

[{"object": "inside an array"}]

Yet, the following JSONs are not,

{"object": "not inside an array"}
{"result": [{"object": "inside an array"}]}

You need to remove the duplicate key element and change it in the following way so you will have an object on the outside.

{
"results": [{
    "oldID": 5,
    "oldMain": "News papers"
}],
"resultss": [{
    "oldID": 3,
    "oldMain": "Construction"
}]}

Here, actually you should have brought you php code, as the problem is with that php code which is sending the JSON. When you want to send the JSON try to make an array of your data. I do the following way.

        $data = [];
        foreach ($results as $res) {
            $t = [];
            $t['oldID'] = $res['oldID'];
            $t['oldMain'] = $res['oldMain'];
            $data[] = $t;
        }
        echo json_encode(['results' => $data]);

You'd better send your php code which is lacking here. My php script does not contain all of your code, but it gives you idea how to do it.

like image 29
H. M.. Avatar answered Dec 08 '25 06:12

H. M..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!