SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

โดย SONGCHAI SAETERN

วิธีแก้ปัญหา SyntaxError: JSON.parse: unexpected non-whitespace character

ปัญหาที่เกิดขึ้นคือ เมื่อมีการ submit ผ่าน iframe และให้ PHP คืนค่าเป็น JSON

$json = json_encode(array(
                                    "is_successful" => FALSE,
                                    "message" => $message
));
echo $json;
ผลที่ได้คือ หน้าเว็บค้าง ไม่มีอะไรตอบสนองหรือทำงานต่อจากนั้นเลย และเมื่อเปิด console ขึ้นมาดูก็พบข้อความแจ้ง error ดังนี้

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 921 of the JSON data
ทั้งที่ค่าคืนกลับมาใน iframe ก็ปกติดี



โค้ดในส่วนของการดึงข้อมูลใน iframe หลังจาก Submit เรียบร้อยมีดังนี้
var c = 0;
$("#post_iframe").on('load',function() {
c++;
if(c==1){
iframeContents = this.contentWindow.document.body.innerHTML;
var json_string = iframeContents.toString();
if(json_string != ""){
var results = jQuery.parseJSON( json_string ); if(results.is_successful){
//SUCCESS
}else{
//FALSE
} }else{
alert('การดำเนินการล้มเหลว กรุณาลองใหม่อีกครั้ง');
}
}
});

และจุดที่เกิด error ก็คือ

var results = jQuery.parseJSON( json_string );

ก็ลองค้นจนเจอกระทู้หนึ่งแนะนำว่าให้แปลงโค้ดก่อน
var decoded = $("<div/>").html(encodedStr).text();

ก็จะได้โค้ดดังนี้
var c = 0;
$("#post_iframe").on('load',function() {
c++;
if(c==1){
iframeContents = this.contentWindow.document.body.innerHTML;
var json_string = iframeContents.toString();
if(json_string != ""){
var json_string = $("<div/>").html(json_string).text();
var results = jQuery.parseJSON( json_string ); if(results.is_successful){
//SUCCESS
}else{
//FALSE
} }else{
alert('การดำเนินการล้มเหลว กรุณาลองใหม่อีกครั้ง');
}
}
});

เป็นอันเสร็จพิธี!!


แต่เดี๋ยวก่อน ถ้าท่านยังเจอปัญหานี้อยู่
JSON.parse: expected property name or '}'

ปัญหาจะเกี่ยวกับ Double / Single Quotes ให้ลองแก้ตามนี้ดู



Change:JSON.parse("{'wrongQuotes': 5}")


To:

JSON.parse('{"rightQuotes": 5}')





อ้างอิง

How to decode HTML entities using jQuery?
https://stackoverflow.com/questions/1147359/how-to-decode-html-entities-using-jquery

JSON.parse: expected property name or '}'
https://stackoverflow.com/questions/8013582/json-parse-expected-property-name-or