3

I am using json_encode to convert the array to json. But json is giving braces {} if value is blank for some key . I want the value should come null or "" blank. Please help .Below is the code :

<?php
$postData='<Lead>
<General>
<dealer></dealer></General> </Lead>';
 $array_data = json_encode(simplexml_load_string($postData));
$array_data=json_decode($array_data) ;
$dealer=$array_data->General->dealer;
$data=array('dealer'=>$dealer);
echo  $objectJson =json_encode($data);
?>


response is : {"dealer":{}}
2
  • Try checking your contents before encoding it. Commented Jan 6, 2017 at 9:40
  • 1
    You are looking at the wrong place, simplexml_load_string generates empty objects so json_encode() correctly encodes them to {}: eval.in/710579 Commented Jan 6, 2017 at 9:41

1 Answer 1

2

It's because your $dealer is an empty array which in json is same as {}

Use ternary

'dealer'=>((!$dealer) ? $dealer : null)

this means that if $dealer is empty assign a null which will change your empty array or {} in json to a null

$data=array('dealer'=>((!$dealer) ? $dealer : null));

also

echo  $objectJson =json_encode($data);

if you just display it and not use it again in code below avoid declaring it instead just display it

echo json_encode($data);
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.