I am using yii1. I have following code which converts array into json:
public function actionIndex()
{
/* $this->layout='//layouts/datatable';*/
if(Yii::app()->request->isAjaxRequest) {
$model = Company::model()->findAll();
$data = array_map(function ($model) {
return $model->attributes;
}, $model);
$responce = json_encode($data);
var_dump($responce);
return $responce;
}
else {
return $this->render('list');
}
}
It returns json data string(1221) "[{"c_id":"1","c_name":"Marokand", ...
However, i need json data with the following format:
[{c_id: 1, c_name: "Marokand",
Please, help me.
Use echo instead of var_dump().
Instead of return, i used echo. It gave me expected result.
Related
I have a Symfony project where I want to store the all the rows from my MySQL table to JSON. Currently there are five rows in my table, but in my browser it only returns five empty values as {"results":[{},{},{},{},{}]}
I guess I have done something right, but not everything. What am I missing in my code?
#[Route('/budget/api', name: 'budget-api')]
public function index(Request $request, BudgetRepository $repository)
{
$results = $repository->findAll();
return $this->json(['results' => $results]);
}
Try createQueryBuilder its usefull.
#[Route('/budget/api', name: 'budget-api')]
public function index(Request $request, BudgetRepository $repository)
{
$qb = $repository->createQueryBuilder("b");
$results = $qb->getQuery()->getArrayResult();
return $this->json(['results' => $results]);
}
You can use the serializer or re-create the array yourself like that
$courses = $doctrine->getRepository(Course::class)->findByLikeTitle($search, $userId);
foreach ($courses as $key => $course) {
$jsonCourses[$key]['title'] = $course->getTitle();
}
```
You can achieve this by Using a Serializer to convert the array of objects into JSON. There are other ways to achieve this like using jsonResponse for example. But the serializer is the most robust way imo.
Example only:
use Symfony\Component\Serializer\SerializerInterface;
#[Route('/budget/api', name: 'budget-api')]
public function index(Request $request, BudgetRepository $repository, SerializerInterface $serializer)
{
$results = $repository->findAll();
$jsonResults = $serializer->serialize($results, 'json');
//If you need to handle any circular references, you can use this..
$jsonResults = $serializer->serialize($results, 'json', array(
'circular_reference_handler' => function ($object) { return $object; },
));
return $jsonResults;
}
About this code, define an API endpoint to get post detail:
/posts/{post}
public function show($post)
{
return DB::table('posts')->where('id', $post)->get()->map(function($s){
$s->type = __(Post::TEXT[$s->type]);
return $s;
});
}
It return json like this:
[
{
"id": 1,
"name": "Test"
}
]
Want to return data like this:
{
"id": 1,
"name": "Test"
}
So added ->first() to the end of the method:
public function show($post)
{
return DB::table('posts')->where('id', $post)->get()->map(function($s){
$s->type = __(Post::TEXT[$s->type]);
return $s;
})->first();
}
But got error:
(1/1) UnexpectedValueException
The Response content must be a string or object implementing __toString(), "object" given.
How to do?
To make sure that an api route correctly returns a json response, use the json response helper. This will try to parse any data and add the correct headers.
public function show($post)
{
$post = DB::table('posts')->where('id', $post)->get()->map(function ($s) {
$s->type = __(Post::TEXT[$s->type]);
return $s;
})->first()
return response()->json($post);
}
You can instead of returning just the map function result, you can cast that into an object like this:
$result = DB::...
return (object) $result;
Why can not I use '%' or '' in LIKE query builder to select all data?
I try in SQL shell can, but in query builder can not
My Model
public function ajax_getTargetMhs($where,$where2) {
$this->db3->SELECT("nim,nama,kodeunit")
->FROM("akademik_ms_mahasiswa")
->LIKE('kodeunit',$where)
->LIKE('periodemasuk',$where2);
$query = $this->db3->get();
if( $query->num_rows() > 0 ) {
return $query->result();
} else {
return array();
}
}
My Controller
public function getTargetMhs($where,$where2) {
$json =$this->Survey_Model->ajax_getTargetMhs($where,$where2);
$arr = array();
foreach ($json as $results) {
$arr['data'][] = array(
$results->nim,
$results->nama,
$results->kodeunit
);
}
//save data mysql data in json encode format
echo json_encode($arr);
}
I can't access like this
'ajax': "<?php echo base_url(); ?>survey/getTargetMhs/"+'SINF/'+'%',
The method like() accepts a third parameter that describes which "side" of the "matching" string to put wildcard characters on. Acceptable values are 'none', 'left', 'right', 'both'.
If you don't pass a "side" value then 'both' is used. Not sure which is the correct choice for you. If you want to construct the whole matching argument yourself then 'none' should work.
Documentation on like() HERE
I try to return as json added attribute which I get with the following method in my User model but I keep getting
"message": "Malformed UTF-8 characters, possibly incorrectly encoded",
"exception": "InvalidArgumentException",
"file": "/var/www/timetool/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php",
the code
/**
* #return string
*/
public function getAvatarImageAttribute($value)
{
if($this->hasMedia('avatar')) {
$image = $this->getMedia('avatar');
$img = \Intervention\Image\ImageManagerStatic::make($image[0]->getPath())->encode('data-url');
}
elseif (isset($this->blob->dokument)) {
$img = 'data:image/jpeg;base64,'. base64_encode($this->blob->document);
} else {
$img = '';
}
return $img;
}
in controller I have
return \Response::json($users, 200, array('Content-Type' => 'application/json;charset=utf8'), JSON_UNESCAPED_UNICODE);
I'm thinking it's related to JSON needing only UTF8 chars and your blob may have invalid chars. Try utf8_encode($img). http://at2.php.net/manual/en/function.utf8-encode.php
In your controller just return. Laravel will build a proper json response for you.
Paste this function top of your document:
public static function convert_from_latin1_to_utf8_recursively($dat)
{
if (is_string($dat)) {
return utf8_encode($dat);
} elseif (is_array($dat)) {
$ret = [];
foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);
return $ret;
} elseif (is_object($dat)) {
foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);
return $dat;
} else {
return $dat;
}
}
Call the above function to convert the content. It has a parameter just it need the value of blob image (binary):
$img = $this->convert_from_latin1_to_utf8_recursively($this->blob->document)
In my case the problem was the encoding of the controller. The solution was to convert it to UTF8 and the bug was fixed.
I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);