簡體   English   中英

SyntaxError:JSON解析錯誤:意外的標識符“object”

[英]SyntaxError: JSON Parse error: Unexpected identifier “object”

請幫我理解什么是錯的。 我想將JSON回復解析為對象。

PHP process.php代碼:

<?php
    $return = array();
        array_push($return['amount']="$amount");
        array_push($return['fee']="$fee");
        array_push($return['total']="$total");
    echo json_encode($return);
?>

返回JSON字符串:

{"amount":"350","fee":"0","total":"350"}

JS(jquery)代碼:

$.getJSON("process.php?amount="+amount, function(data,status) {
   var obj = $.parseJSON(data);
   alert (obj.amount);
});

我收到錯誤:

SyntaxError:JSON解析錯誤:意外的標識符“object”

但! 當我嘗試插入結果而不是數據時(但是左/右插入'引號):

var obj = $.parseJSON('{"amount":"350","fee":"0","total":"350"}');

而且我看到警報= 350.所以,它運作良好。

我試着做出類似的東西:

var jsonreply = "'"+data+"'";
var obj = $.parseJSON(jsonreply);

但收到以下錯誤:

SyntaxError:JSON解析錯誤:JSON中不允許使用單引號(')

getJSON為你解析JSON - 調用$.parseJSON會將對象轉換為字符串[object Object] ,然后嘗試解析它,給你一個錯誤。 只需省略$.parseJSON調用並直​​接使用data


此外,我應該注意到對array_push的調用很奇怪而且沒必要。 array_push通常需要一個數組和一個值來推送它,但是(例如)在你的第一行中你將$return['amount']"$amount"然后將$return['amount']傳遞給array_push ,它什么都不做,可能會給你一個警告或錯誤。 如果你這樣做,你會得到完全相同的行為:

$return['amount']="$amount";
$return['fee']="$fee";
$return['total']="$total";

然后你可能也會意識到, "$amount"周圍的引號是不必要的,你實際上可以這樣做:

$return['amount']=$amount;
$return['fee']=$fee;
$return['total']=$total;

最后,您可以非常輕松地使用一些特殊的array語法壓縮所有五行:

echo json_encode(array(
    'amount' => $amount,
    'fee' => $fee,
    'total' => $total
));

如果我自己這么說的話,那就更好了。

其實你不需要解析它。 你可以直接訪問它

$.getJSON("process.php?amount="+amount, function(data,status) {
 alert (data.amount); 
});

看起來你的錯誤就在這里:

var jsonreply = "'"+data+"'";

試着逃避那些'與'\\“。 喜歡

var jsonreply = "\'"+data+"\'";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM