[英]How to return encoded json with json object in json codeigniter rest server
I am using the codeigniter rest by phil sturgeon. 我正在使用菲尔·urge鱼的codeigniter支架。
I want to return a JSON object that contains another JSON object within. 我想返回一个JSON对象,其中包含另一个JSON对象。
My code looks like this 我的代码看起来像这样
function volunteer_get()
{
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
$this->load->model('user/users_model');
$user = $this->users_model->get( $this->get('id') );
$address = $this->address_model->getAddress( $this->get('id') );
$user->address = $address;
$userJson = json_encode($user);
var_dump($userJson);
/*if($user && $user->auth_level == 1)
{
$this->response($userJson, 200); // 200 being the HTTP response code
}
else
{
$this->response(NULL, 404);
}*/
}
It is not showing any result... If i do this without adding the php object in the other php object, it shows me the json! 它没有显示任何结果...如果我在不将php对象添加到其他php对象中的情况下执行此操作,则会显示json!
D:\wamp\www\codeigniter\application\controllers\api\Users.php:37:string '{"user_id":"1","username":"abc","email":"abc","auth_level":"1","banned":null,"passwd":"abcdefg","passwd_recovery_code":"abcdefg","passwd_recovery_date":"2017-06-12 18:50:31","passwd_modified_at":"2016-11-18 21:20:30","last_login":"2017-08-30 15:10:36","created_at":"2016-09-02 12:01:46","modified_at":"2017-08-30 15:22:45","first_name":"aze","family_name":"'... (length=1354)
In general, you need to check whether you got a JSON object (usually a PHP dictionary or object) or a JSON representation (a string). 通常,您需要检查是否有JSON 对象 (通常是PHP字典或对象)或JSON 表示形式 (字符串)。
You can not add a string to another string. 您不能将一个字符串添加到另一个字符串。 And if you add a string to a dictionary or object, it won't be properly encoded as a JSON sub-object because it is, well, a string.
而且,如果您将字符串添加到字典或对象中,则由于它是字符串,因此无法正确编码为JSON子对象。
So if you have a representation, you have to decode it first : 因此,如果您有一个表示形式,则必须先对其进行解码 :
// Here, $dataOne is a string, and $dataTwo is too.
// we decode to array rather than to object (see manual for json_encode)
$dataOneJSON = json_decode($dataOne, true);
$dataTwoJSON = json_decode($dataTwo, true);
$dataOneJSON['two'] = $dataTwoJSON;
$result = json_encode($dataOneJSON);
$this->response($result, 200);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.