Skip to content
Advertisement

Error converting Json string to array of objects PHP

I made a post in a form converting my javascript localstorage to a post request. From there I tried to decode my json string to make an object in PHP.

How my php code looks before I echo it

    $cart_items = $_POST['cart_items'];
    $cart_items = json_encode($cart_items);
    $array_test = json_decode($cart_items);
    print_r($array_test);

What it returns in browser

[{"id":83494890,"title":"2020 Hino 358","partType":"Bumpers","price":100,"stockNumber":12313131312,"thumbImg":"/jOIY91KhEby8_f.jpg","permalink":"/part-description/?part=83494890","maxQuantity":1,"requestedQuantity":"3"}
,{"id":83493833,"title":"2009 Freightliner 5020080","partType":"ABS Modulator Valves","price":150,"stockNumber":"P-1211111111157","thumbImg":"/OOjQbsi6p8kX_f.jpg","permalink":"/part-description/?part=83493833","maxQuantity":1,"requestedQuantity":"1"}]

I know that typically when seeing json data there isn’t forward slashes everywhere. I tried to json_decode into an array rather than an object, then make a foreach for each object inside. But I got this error returned “Invalid argument supplied for foreach()

How do I make this json string convert to an array of objects? Thank you

Advertisement

Answer

It looks like $_POST['cart_items'] already contains JSON. So you just need to decode it, not encode it first.

$array_test = json_decode($_POST['cart_items'], true);
print_r($array_test);

But it’s actually encoded twice, that’s why it has escaped quotes, so you need to call json_decode() twice. But it’s missing the double quotes around the whole thing, and the embedded newline is not valid.

The following works:

<?php
  $cart_items = '"[{"id":83494890,"title":"2020 Hino 358","partType":"Bumpers","price":100,"stockNumber":12313131312,"thumbImg":"/jOIY91KhEby8_f.jpg","permalink":"/part-description/?part=83494890","maxQuantity":1,"requestedQuantity":"3"},{"id":83493833,"title":"2009 Freightliner 5020080","partType":"ABS Modulator Valves","price":150,"stockNumber":"P-1211111111157","thumbImg":"/OOjQbsi6p8kX_f.jpg","permalink":"/part-description/?part=83493833","maxQuantity":1,"requestedQuantity":"1"}]"';
  $array_test = json_decode(json_decode($cart_items));
  print_r($array_test);

I suggest you find the code that’s sending the cart_item POST parameter and fix it so it doesn’t do all this extra encoding.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement