Json Decode Error

I tried parsing this JSON, but I get error using Json::decode


{"po":"11446019431405","orders":[{"product":{"ID":"2","product_name":"A","product_code":""},"ID":"2","product_name":"A","product_code":"","price":"11","qty":1,"discount":0,"subtotal":11,"amount":11},{"product":{"ID":"1","product_name":"B","product_code":""},"ID":"1","product_name":"B","product_code":"","price":"10","qty":1,"discount":0,"subtotal":"10","amount":10}],"grandTotal":21}

What am I doing wrong here?

var_dump gives me


array(1) { ["{"po":"11446021195934","orders":"]=> array(1) { ["{"product":{"ID":"2","product_name":"A","product_code":""},"ID":"2","product_name":"A","product_code":"","price":"11","qty":1,"discount":0,"subtotal":11,"amount":11},{"product":{"ID":"1","product_name":"B","product_code":""},"ID":"1","product_name":"B","product_code":"","price":"10","qty":1,"discount":0,"subtotal":"10","amount":10}"]=> string(0) "" } }

but I get error saying:


PHP Warning 'yii\base\ErrorException' with message 'json_decode() expects parameter 1 to be string, array given' 


in C:\xampp\yii2\controllers\PurchaseController.php:121

Hello corbeeresearch,

decode_json() : the [size=2]input[/size][size=2] param is string.[/size]

As your error, your input param can be array.

If is set json::decode to true, I still get ‘Array to string conversion’ error

$json = '{“po”:“11446019431405”,“orders”:[{“product”:{“ID”:“2”,“product_name”:“A”,“product_code”:""},

"ID":"2","product_name":"A","product_code":"","price":"11","qty":1,"discount":0,"subtotal":11,"amount":11},

{"product":{"ID":"1","product_name":"B","product_code":""},

"ID":"1","product_name":"B","product_code":"","price":"10","qty":1,"discount":0,"subtotal":"10","amount":10}],

“grandTotal”:21}’;

$data = Json::decode($json,true);

var_dump($data);die;

no error with me.

can you post your code on here?

javascript code




$("#w0").on("submit", function (){

			var po = user_id + Date.now();

			orderCollection.po = po;

			$("#po").val(po);

			$.post("index.php?r=purchase/postorders", {"json" : ko.toJSON(orderCollection)}, {}, "json");

			return false;

		});



controller


public function actionPostorders() {

	$request = Yii::$app->request->post();

	echo Json::decode($request['json']);

}

[color="#000000"]echo [/color][color="#660066"]Json[/color][color="#666600"]::[/color][color="#000000"]decode[/color]color="#666600";[/color]

[color="#666600"]Json::decode return an array, you can not use "echo".[/color]

Thanks, I think I got it.