convert json string to variables


convert json string to variables



maybe my question is a bit unreasonable, but what's wrong i ask.



I have a simple script like below


<?php
$r['code'] = 200;
$r['result'] = "hello world";
$r['down'][0] = "first";
$r['down'][1] = "second";
echo json_encode($r, JSON_PRETTY_PRINT);
?>



and the results from the script are


{
"code": 200,
"result": "hello world",
"down": [
"first",
"second"
]
}



as seen above, that variables can be converted to json by using json_encode, and to my question, can we change json back into variables?



for example



Before


{
"code": 200,
"result": "hello world",
"down": [
"first",
"second"
]
}



After


<?php
$r['code'] = 200;
$r['result'] = "hello world";
$r['down'][0] = "first";
$r['down'][1] = "second";
echo json_encode($r, JSON_PRETTY_PRINT);
?>





Look at json_decode... or if in the same script $r should still be accessible.
– user3783243
Jun 30 at 3:14



json_decode


$r





json_encode returns json array but will not actually convert $r unless you do something like $r = json_encode($r, JSON_PRETTY_PRINT); simply put you already have your $r in original form
– Digvijaysinh Gohil
Jun 30 at 3:19



json_encode


$r


$r = json_encode($r, JSON_PRETTY_PRINT);


$r




3 Answers
3



Just use json_decode():


json_decode()


$json = '{
"code": 200,
"result": "hello world",
"down": [
"first",
"second"
]
}';

$r = json_decode($json, true);
print_r($r);



This prints:


Array
(
[code] => 200
[result] => hello world
[down] => Array
(
[0] => first
[1] => second
)

)



yes we can accomplished that by using json_decode()


$a = json_decode($r, true);



True is used to say that we want use regular Array


$array['item']



if false is set, the property will be accessed by using


$array->item



Use json_decode() to convert JSON array to PHP array.


json_decode()


$json_array = '{
"code": 200,
"result": "hello world",
"down": [
"first",
"second"
]
}';

$r = json_decode($json_array);






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV