0

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
3
  • What error does it throw, and what's the code that throws it? Commented Mar 15, 2010 at 9:16
  • Trying to get property of non-object in <b>C:\wamp\www\l\public\grr.php</b> on line <b>21 Commented Mar 15, 2010 at 9:39
  • you are trying to access an array like an object. use $obj['value'] Commented Mar 15, 2010 at 9:51

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

@jason,please don't always leave your questions an unanswered state,and that would be some kinda of negative record.
0

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.

Comments

0

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

3 Comments

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 **
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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.