PHP Program to JSON Key Count with Explanation
PHP
Easy
PHP Error Handling
36 views
1 min read
89 words
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around json, invalid_json, one. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Given a JSON object. If invalid, print INVALID_JSON. Else print how many keys it has.
Input Format
One line json.
Output Format
One integer or INVALID_JSON.
Constraints
Total length
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php
$js=trim(stream_get_contents(STDIN));
if($js==='') exit;
$obj=json_decode($js,true);
if(json_last_error()!==JSON_ERROR_NONE || !is_array($obj)){
echo 'INVALID_JSON';
exit;
}
echo count($obj);
?>
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Given a JSON object. If invalid, print INVALID_JSON. Else print how many keys it has.
Input / Output
Output
One integer or INVALID_JSON.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
<?php
$js=trim(stream_get_contents(STDIN));
if($js==='') exit;
$obj=json_decode($js,true);
if(json_last_error()!==JSON_ERROR_NONE || !is_array($obj)){
echo 'INVALID_JSON';
exit;
}
echo count($obj);
?>
Solutions (0)
No solutions submitted yet. Be the first!