TransWikia.com

json encode and decode is not working in PHP

Stack Overflow Asked by Nallammal T on November 18, 2021

I have one object and i have to convert into array, i have used json encode and json decode but it is not working properly.

my object

$LearningNodesData = '{
        0:"5df31",
        1:"5df32",
        2:"5df33"
    }';

my code

    $LearningNodesData1 =json_decode(json_encode($LearningNodesData,true),true);
echo "<pre>";
print_r($LearningNodesData1);

my expected output

[
  "5df31",
  "5df32",
  "5df33"
]

my ouput

{
    0:"5df1",
    1:"5df2",
    2:"5df3"
}

Here what is wrong

Updated code section

<?php
$LearningNodesData = '{
    "0":"5df31",
    "1":"5df32",
    "2":"5df33"
}';

echo my_json_decode($LearningNodesData);


function my_json_decode($s) {
    $s = str_replace(
        array('"',  "'"),
        array('"', '"'),
        $s
    );
    $s = preg_replace('/(w+):/i', '"1":', $s);
    return json_decode(sprintf('{%s}', $s));
}
?>

4 Answers

If I understand, you want to echo/print array, but no keys? If so:

<?php
$learningNodesData = '{
    "0":"5df31",
    "1":"5df32",
    "2":"5df33"
}';

$decodedLearningNodesData = json_decode($learningNodesData, true);

$noKeysLearningNodesData = json_encode(array_values($decodedLearningNodesData));
print_r($noKeysLearningNodesData);

?>

Will print out:

["5df31","5df32","5df33"]

Answered by JureW on November 18, 2021

If you are converting an object into array, it will always return with keys

    $LearningNodesData = '{
    "0":"5df31",
    "1":"5df32",
    "2":"5df33"
    }';
   $arr = json_decode($LearningNodesData,true);
   print_r($arr);
  //output
  Array
  (
    [0] => 5df31
    [1] => 5df32
    [2] => 5df33
  )

In the end array without a key or with the key doesn't matter (if it is numeric key). Your desired output is without key but you will access with their index position.

If you don't want it as array you can make it into comma formatted string using imploade() function

echo imploade(',',$arr); //5df31,5df32,5df33

Answered by DEEPAK on November 18, 2021

You are trying to encode/decode a dictionary and your expected result is a list. If your desired result is a list then try this!

$LearningNodesData = '["5df31","5df32","5df33"]';

Not this

$LearningNodesData = '{
    0:"5df31",
    1:"5df32",
    2:"5df33"
}';

Answered by Sameed Ahmed Siddiqui on November 18, 2021

Your string is not a valid json.

Valid json would be:

$LearningNodesData = '{
    "0":"5df31",
    "1":"5df32",
    "2":"5df33"
}';

you can read this: php json_decode fails without quotes on key maybe you find the solution

Answered by Burhan Ibrahimi on November 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP