Viewed   91 times

I'm trying handle bad json data when parsed through json_decode(). I'm using the following script:

if(!json_decode($_POST)) {
  echo "bad json data!";
  exit;
}

If $_POST equals:

'{ bar: "baz" }'

Then json_decode handles the error fine and spits out "bad json data!"; However, if I set $_POST to something like "invalid data", it gives me:

Warning: json_decode() expects parameter 1 to be string, array given in C:serverwwwmyserver.devpublic_htmlrivrUIpublic_homeindex.php  on line 6
bad json data!

Do I need to write a custom script to detect valid json data, or is there some other nifty way to detect this?

 Answers

2

Here are a couple of things about json_decode :

  • it returns the data, or null when there is an error
  • it can also return null when there is no error : when the JSON string contains null
  • it raises a warning where there is a warning -- warning that you want to make disappear.


To solve the warning problem, a solution would be to use the @ operator (I don't often recommend using it, as it makes debuging a lot more harder... But here, there is not much of a choice) :

$_POST = array(
    'bad data'
);
$data = @json_decode($_POST);

You'd then have to test if $data is null -- and, to avoid the case in which json_decode returns null for null in the JSON string, you could check json_last_error, which (quoting) :

Returns the last error (if any) occurred by last JSON parsing.


Which means you'd have to use some code like the following :

if ($data === null
    && json_last_error() !== JSON_ERROR_NONE) {
    echo "incorrect data";
}
Friday, December 23, 2022
5

Try something like this:

//initialize array
$myArray = array();

//set up the nested associative arrays using literal array notation
$firstArray = array("id" => 1, "data" => 45);
$secondArray = array("id" => 3, "data" => 54);

//push items onto main array with bracket notation (this will result in numbered indexes)
$myArray[] = $firstArray;
$myArray[] = $secondArray;

//convert to json
$json = json_encode($myArray);
Friday, December 23, 2022
2

Modify your function to send header of JSON_DATA in post request

function sendPostData($url, $post){
 $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($post))                                                                       
   );  
  $result = curl_exec($ch);
  curl_close($ch);  // Seems like good practice
  return $result;
}

In file use

<?php

$json_input_data=json_decode(file_get_contents('php://input'),TRUE);

print_r( $json_input_data);


?>

As everyone said there is no need of $str_data = json_encode($data);,Since data is already in json.

Tuesday, November 8, 2022
1

Just use json_encode function

echo json_encode($row);
Tuesday, September 6, 2022
4

you can use it like this, in JSON format when you evaluate false value it will give you blank, and when you evaluate true it will give you 1.

$str = '[{"clientId":"17295c59-4373-655a-1141-994aec1779dc","channel":"/meta/connect","connectionType":"long-polling","ext":{"fm.ack":false,"fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"},"id":"5"}]';

$arr = json_decode($str,true);

if($arr[0]['ext']['fm.ack'])    // suggested by **mario**
{
    echo "true";    
}
else {
    echo "false";   
}
Thursday, October 6, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :