Skip to main content

PHP

 How to validate JSON data in php 8.2 (earlier than PHP 8.3)?

Challenge: 

    If JSON is valid PHP will return associated array or std object against running json_decode($data) function. But, when receive invalid JSON it won't return associated array or std php object. So, i couldn't retrieve data from received string.

Perplexity suggestion: 

 1. First option


    if ($data === '' || ($decoded = json_decode($data, false)) === null && json_last_error() !== JSON_ERROR_NONE) {
    	echo "Invalid JSON";
    }
   

2. Second option


   try {
   	$decoded = json_decode($data, false, 512, JSON_THROW_ON_ERROR);
   } catch (JsonException $e) {
	echo "error messege".$e->getMessage();
   }
   

3. Third option 


function isValidJson(string $data): bool { json_decode($data); return json_last_error() === JSON_ERROR_NONE; }
 

These three option not worked. Means first option not returned "Invalid JSON"and second option not throw error.like that third option also not return false. After few time, i realized if json is invalid json_decode($JSON); functionreturn only string so i just check what is the return value data type and responded client to invalid json (4XX) error.

Comments

Popular posts from this blog

Inventory management system project.

 Objective:       Enable efficient tracking and management of store inventory to ensure products are available when needed. Technology:  PHP 8.2 Codeigniter framework 4.6.1 Codeigniter shield (Auth library) 1.1.0  Firecamp for restAPI testing  Notepad++ code writing (light weight) mySQL  Plan: First people will authenticate using email and password then, Other API access by using Bearer token.    Challenges: Product can measured by different property - {weight, size or volume} Product amount will vary occasionally - {festival, demand} Types of inventory operation - {add, sale, return, remove, adjust, transfer} 1.First challenge:        Whenever measure one material in different measurement then, That material is different product because, It may be in different phase [solid, liquid, gas]. Example- when buying fruit in solid measured as kg , if buying fruit measured in volume. So, same fruit come under different p...