tags:

views:

449

answers:

3

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as

$json = '{"value":"somevalue"}';

Using this:

<?php 
      $json = '{"value":"somevalue"}';
      $obj = json_decode(json_encode($json));
      print $obj->{'value'};
?>

But when i try an get a value from the following json string it throws an error...

$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';

I validated the json on JSONlint but not sure how to access the values within this with php.

  • Thanks
A: 

You can pass true as a second parameter to json_decode() to get the results as an array

$my_arr = json_decode($json, true);
var_dump($my_arr);

Should help you. You can then step through the array as you would normally.

jackbot
A: 

use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

knittl
thats not my problem, I can print out all the values but i am unable to access one of the values:<pre>$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';$json = json_encode($json);$obj = json_decode($json,true);print $obj -> {'field'};</pre>**Trying to get property of non-object in <b>C:\wamp\www\l\public\grr.php</b> on line <b>21**
jason
If you pass `true` to `json_decode()`, it'll give you back an array, not an object. You need to access elements in the way you normally would for an array.
jackbot
@jason First, please do not post code in comment fields, it's messy. :) Second, when using `json_decode(..., true)`, the result is indeed not an object, but an array. Yet you're trying to access it like an object. The error message is quite correct.
deceze
+2  A: 

You can try this:

$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}'; 
//since $json is a  valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
SpawnCxy
that worked! sweet.. thanks
jason
@jason,please don't always leave your questions an unanswered state,and that would be some kinda of negative record.
SpawnCxy
oh right, he does double encoding. good catch!
knittl