Get {} as an output instead of [] - php

I have service which returns the menu of venues, but if menu is not exist, I should return {} as an output, otherwise ios app cannot parse the response and app destroys.
Now reponse looks like:
{
"response": []
}
I should have
{
"response": {}
}
API services programmed with PHP.
When menu empty url: http://ilovejetset.com/api/v2/menu/index/422
When some menu exist: http://ilovejetset.com/api/v2/menu/index/423
The code for creating response:
in 'after' function:
$this->response->body(json_encode(array('response' => $this->response_json)));
when no menu:
$this->response_json = array();

Check out this page:
Predefined Constants (JSON) More specifically JSON_FORCE_OBJECT
If the data which is deeper than responses needs to be an array then you will need to loop over first encode all of that data, then encode the top layer.
$test = array(
"responses" => array()
);
echo json_encode($test, JSON_FORCE_OBJECT);

If you need an object, then you need to create an object in PHP as well. As long as you're using arrays, PHP will preferably encode them as JSON arrays.
$data = new stdClass;
$data->foo = 'bar';
echo json_encode(array($data));
or:
echo json_encode(array((object)array('foo' => 'bar')));

if you use json_encode this function, you can try to add the option JSON_FORCE_OBJECT as fllows.
<?php
$var = array();
$var['response'] = array();
echo json_encode($var, JSON_FORCE_OBJECT);
$var1 = array();
$var1['response'] = array();
$var1['response']['name'] = 'jediliang';
echo json_encode($var1, JSON_FORCE_OBJECT);
?>
the output looks like this:
{"response":{}}{"response":{"name":"jediliang"}}

For more clarification try this following example
class a {
var $name;
};
$a = new a;
$a->name = array("name"=>"fname");
echo json_encode(array("a"=> $a, "name"=>array("fname","lname")));
Hope it clears all your doubts

Related

How can I convert an object to a specific JSON format?

json_encode converts an object to:
{
"height":10,
"width":20,
"depth":5
}
But I need it to include the objects class name as well:
{
"cuboid":
{
"height":10,
"width":20,
"depth":5
}
}
public function toJson() {
return json_encode([get_class($this) => $this]);
}
Hope this will help you out. Here we are converting json to array and putting it into an array of field cuboid
Try this code snippet here
<?php
ini_set('display_errors', 1);
$json='{
"height":10,
"width":20,
"depth":5
}';
$result["cuboid"]=json_decode($json,true);
echo json_encode($result,JSON_PRETTY_PRINT);
You can use get_class to get class name of an object.
$json = json_encode(array(get_class($object) => $object));
Rules for json_encode
if you have an object it will be encode to {'pro1':'value'}
if you have an array it will be encode to ['value']
if you have an string it will be encode to 'value'
Note: If you have an assoc-array in php, it becomes an object in json! If you have an index-array it will be an array in json. Dont mix index & assoc!
Test this bad pratice: echo json_encode(array('foo' => 'bar',1,2)); Result is this bad syntax {"kitten":"test","0":1,"1":2} (propertie-names should NOT be numbers !!!)
So if you want and object under a property name do this
$obj = new stdClass();
$obj->prop = array(1,2,'a');
$newObject = new stdClass();
$newObject->objname = $obj;
print_r(json_encode($newObject));
Becomes: {'objname':{'prop':[1,2,'a']}}
Have a nice day :-)

How to iterate the JSON data into a loop using PHP?

I need to iterate some JSON formatted data into loop using PHP. My JSON data is below:
{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}
I need to run the loop so that the result data will come in above format using PHP.
Convert the php object to json object using json_encode
// convert object => json
$json = json_encode($myObject);
This might helpful: https://stackoverflow.com/a/9858457/6285410
What you showed us is a Possible JSON Data. In this Format, we can do nothing with it in PHP except by decoding back into Native PHP Object. Once that is done, You can access all the Properties of the Object like you do with normal PHP Object like $objData->questin1. Here's what is meant with the above statements:
<?php
$strJson = '{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}';
$objData = json_decode($strJson);
var_dump($objData);
// NOW, TO GET AT EACH OF THE PROPERTIES OF THE OBJECT IS EASY...
// ACCESS THE question1 OR question2
$q1 = $objData->question1;
$q2 = $objData->question2;
// ACCESS THE que WITHIN question 1 OR question2
$k1 = $objData->question1->ques; // EQUIVALENT TO: $q1->ques
$k2 = $objData->question2->ques; // EQUIVALENT TO: $q2->ques
// ACCESS THE optional ARRAY INSIDE OF question 1 OR question2
$opt1 = $objData->question1->optional; // EQUIVALENT TO: $q1->optional
$opt2 = $objData->question2->optional; // EQUIVALENT TO: $q2->optional
var_dump($q1, $q2, $k1, $k2, $opt1, $opt2);
?>

Accessing object property by variable in php

Objectives:
I am trying to read certain parts of any json file by letting the user input the desired properties.
Say I have an object that looks like this:
"adverts": [
{
"id": "33655628",
"companyInfo": {
"companyName": "Company A",
"homepage": "http://companya.com",
"companyText": null
},
...
]
I want to access the properties by assigning the property name or "path" by a variable.
Accessing the first level ($item->$_id) works fine but how do I access a nested property companyName directly with by a variable such as
$_name = "companyInfo->companyName";
Ex:
$_repeat = "adverts";
$_id = "id";
$_name = ??????
foreach($data->$_repeat as $item){
var_dump($item->$_id);
var_dump($item->$_name);
}
EDIT:
As clarification: I want this to be universal for any JSON object!
PRELIMINARY SOLUTION:
I got the desired results by looping as suggested by #Carlos:
$_title_a = explode(".",$_title);
$current = $document;
foreach($_title_a as $a){
$current = $current->$a;
}
var_dump($current);
If someone has a better suggestion, I would be glad to hear it. Thanks everybody!
Why do you exactly need this?
All you have to do is:
$jsonData = json_decode($jsonString, true);
echo $jsonData['adverts'][0]['companyInfo']['companyName'];
//or
foreach($jsonData['adverts'] as $advert){
echo $advert['companyInfo']['companyName'];
}
It seems that you have json data with you..you can use below code..
$obj= json_decode($yourJsonData);
print_r($obj);
foreach ($obj as $key => $value) {
$companyinfo = $value['companyInfo']['companyName'];
}
In foreach loop you will get require key and values..this is just a example for you..

decode multiple json object php

I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.

php/zend/json: How to fetch view then pass it as json object?

On the view, there is this basic javascript/jquery:
$('#jsoncallbtn').click(function() {
$.post('/mycontroller/json', {
someint: 123,
somestr: 'string'
}, function(datafromserver) {
alert(datafromserver.data1); // prints "test"
alert(datafromserver.data2); // prints "null"
}, "json");
});
On server side:
public function jsonAction()
{
$jsonArray = array('data1' => 'test',
'data2' => $this->render('anotheraction'));
$this->_helper->json($jsonArray);
}
Is there a way to render another action view and send it back for javascript as part of json object?
Sounds like the Action View-Helper could do the job.
You could create a separate Zend View instance and add the view's output to the JSON array. E.g something on along the lines of:
$view = new Zend_View();
$view->variable = "testing 123";
$html = $view->render('path/to/view/file.phtml');
$jsonArray["html"] = $html;
Zend_Json::encode($jsonArray);

Categories