简体   繁体   中英

How to get values of encoded json using php in ajax response?

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

Hi, I am getting a JSON data as below using the above PHP code.

var result = {"out":"[{\"tax\":\"SGST@9%\",\"percent\":7.75},{\"tax\":\"CGST@9%\",\"percent\":7.75},{\"tax\":\"SGST@2.5%\",\"percent\":3.11},{\"tax\":\"CGST@2.5%\",\"percent\":3.11}]","total":210}

I need to get the elements in a separate variable like below

var out = [{"tax":"SGST@9%","percent":7.75},{"tax":"CGST@9%","percent":7.75},{"tax":"SGST@2.5%","percent":3.11},{"tax":"CGST@2.5%","percent":3.11}];
var total = 210;

I tried so far with the below codes.

result = JSON.stringify(result);
result = result.replace(/\\/g, "");
var obj3 = JSON.parse(result);
alert(obj3[0]);

But i am not getting any output.

The basic problem is that $out is JSON to start with (so it ends up being double encoded), but it doesn't make sense for it to be JSON in the context.

You could just convert it to a PHP data structure before converting the wider array to JSON:

$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";

If you don't want to touch the PHP, you can work around that in JavaScript:

$out = json_decode($out, true);
$json = json_encode(array('out' => $out, 'total' => $total ));
echo "var result = $json;";
?>
var out_json = result.out;
var out = JSON.parse(out_json);

In your Ajax setup, add JSON

dataType: 'JSON', 

Then in your success function,

success: function(result) {
console.log(result.tax);//gives you the value for the tax key provided it's defined in the php response array
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM