am pretty new to json and i have this data that i would like to pass to a view script..the data comes from an sql query i have executed as below:
public function get_specific_users($param)
{
$select=new \Zend\Db\Sql\Select;
$select->from('users');
$select->columns(array('username','password','firstname','lastname','reputation'));
$select->where(new \Zend\Db\Sql\Predicate\Like('username',$param. "%"));
$resultSet=$this->tableGateway->selectWith($select);
return $resultSet;
}
this is how i call the function from my controller:
$users=$this->getUserTable()->get_specific_users('jo');
return new JsonModel(array('data' =>$users));
can i be able to pass the $users as above or should i first convert the resultset to an array..?if not how can i go about it..thanks in advance..
okay..i did more research and got it..had to include the following:
$users=$this->getUserTable()->get_specific_users('jo');
$result = \Zend\Json\Json::encode($users);
return $result;
the output was pretty clean json data which i can now parse using jquery..
Related
Mostly this is about just sending hard coded JSON from Web API method back to a caller app ( happens to be React). My current action looks something like the following:
[Route("members/{memberId}")]
public async Task<IActionResult> Members(string memberId)
{
// {
// "SecA4": ["Asian"]
// }
// ?? string json = "{ \"SecA4\": [\"Asian\"] }"; //??
return OK() // need to place JSON in the OK() method. but how should it be done?
}
So currently I am able to load from a file into a survey engine a file that looks like that. Thus I load from a .json file.
{
"SecA4": ["Asian"]
}
Rather then a hard-coded string I would use an object rather, which would be done something like the following
object someObject = new
{
SecA4 = "Asian"
};
You can create this pretty much the same way as you would do with Json.
Now we are just returning the newly created object and converting it into Json.
return Json(someObject, new JsonSerializerSettings() { Formatting = Formatting.None });
Where in the JsonSerializerSettings you can tell Newtonsoft.Json to no use any formatting e.g. new lines, spaces and so on.
I want to pass this JSON data to some view but don't know how its works.
I have used, make view also, and convert this data to JSON and pass other way but it didn't work
$items = Items::all();
return response()->JSON($items);
e.g view is items.create
For Laravel ver 4.2,
You can pass your data to your blade view with a variable (eg:$data) having an array which will be used in your blade.
$flag is variable being used in the JS part of your code, so you can pass that also as an array: Response::json(['param1' => $foo1, 'param2' =>$foo2)]);
In your controller return the view:
return Response::json(['view' => View::make('yourbladename', $data)->render(), 'flag'=>$flag]);
In your JS use the data variables as:
function(data){
$('#DivToAppendHTML').append(data.view); //this appends html blade to the Div having the ID DivToAppendHTML
if(data.flag == 1){ //this uses the second variable passed in controller for any other purpose
$('.classname').remove();
}
}
If you want to create JSON response, you need to convert collection to an array:
$items = Items::all()->toArray(); // $items is array now
return response()->json($items);
If you want to pass some JSON data to a view, do this:
$items = Items::all()->toJson();
return view('items.create', compact('items'));
How do you create a custom JSON output with FOSRestBundle?
The code already has methods which are used to convert entities and paginated result sets to JSON. As well as generate unique URLs to view/edit the entities in the outputted JSON.
How can these be used with FOSRestBundle?
Example of custom method to convert Bars to JSON output:
$json = $this->getJsonFactory('Bar')
->dataTableFormat($data);
return $this->jsonResponse($json);
How can this custom method be used as the output for JSON from view?
$data = $this->getDoctrine()->getRepository('Foo:Bar')
->findAll();
$view = $this->view($data, 200)
->setTemplate("Foo:Bar:index.html.twig")
->setTemplateVar('bars')
;
JMSSerializerBundle is available if it helps.
Using custom handlers this is possible, see docs: http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler
Working example:
$handler = $this->get('fos_rest.view_handler');
if (!$handler->isFormatTemplating($view->getFormat())) {
$templatingHandler = function ($handler, $view, $request) {
$data = $this->getJsonFactory('Bar')
->dataTableFormat($$view->getData());
$view->setData($data);
return $handler->createResponse($view, $request, 'json');
};
$handler->registerHandler('json', $templatingHandler);
}
The $templatingHandler method handles calling the JsonFactory and setting the formatting of data for json output.
I'm trying to read and output a json from database. I insert a json using something like this:
$widget->settings = json_encode($input->get('settings'));
Then when I read I try with:
$settings = json_decode($response->settings);
However I get an escaped string and not a valid json. This is what I got:
"settings":"{\"url\":\"http:\\\/\\\/www.google.com\"}"
But I was expecting something like:
"settings":{"url":"http:\/\/www.google.com"}
[EDIT]
I've tried also to add this to my model:
public function getSettingsAttribute()
{
return (array)json_decode($this->settings);
}
But I got error:
Undefined property: Widget::$settings
Using this solve the problem:
public function getSettingsAttribute($value)
{
return json_decode($value);
}
you can use this with the success text:
return response()->json(array("notification" => "success", "data" => json_decode($yourdata->info)));
I am trying to access a REST Service in my MVC application.I am calling getJSON method to get the data from a controller which internally calls the REST service which returns data in json format.But I am getting the a lot of "\ in my output of DownLoadString method and my return Json is not returning proper JSON data and hence my client side script is not able to access the JSON properties.
My Script in my view is
$.getJSON("#Url.Action("GetManufacturers", "Home")",function(data){
console.debug("Status is : "+data.Status)
});
My Action method looks like this
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
//data variable gets "\" everywhere
return Json(data,JsonRequestBehavior.AllowGet);
}
}
I used visual studio breakpoints in my action method and i am seeing a lot of \"
And i checked what is coming out to my getJSON callback and the JSON tab is empty.
But my response tab has content like this
I belive if there is no \", i would be able to parse it nicely.
I used fiddler to see whether i am getting correct (JSON format) data from my REST service and it seems fine.
Can anyone help me to tackle this ? I would like to return proper JSON from my action method. Sometime i may want to read the json properties in the C# code itself. I saw some example of doing it with DataContractJsonSerializer. But that needs a concrete type to be converted to. I don't want to do that. because other clients would also access my RESTService and how will expect them to write a fake entity for this ?
You need to return the data as is:
public ActionResult GetManufacturers()
{
string restURL ="http://mytestserver/myapi/Manufacturers";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
return Content(data, "application/json");
}
}