2

Is there a way to retreive a key from JSON string with out going in to foreach loop?

$json ="{\"error\":{\"code\":301}}";

if (empty($json)) {
    die('empty string');
} else {
    $obj = json_decode($json);
    foreach ($obj as $key => $object) {
        echo $key;
    }  
}

What I need is to detect where the string contains error or not, so I can create error handling.

Thanks in advance

1 Answer 1

1

You can use property_exists() method:

$json ="{\"error\":{\"code\":301}}";


if (empty($json)) {
    die('empty string');
} else {
    $obj = json_decode($json);
    var_dump(property_exists($obj, 'error'));
}
Sign up to request clarification or add additional context in comments.

Comments

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.