i create a route with json_respone function.
the code:
/**
* #Route("/app/homec")
*/
public function HomeCatsAction(Request $request) {
$list = $this->getDoctrine()
->getRepository('AppBen2Bundle:HomeCategories')
->createQueryBuilder('e')
->getQuery()->getArrayResult();
$response = new JsonResponse($list);
$response->headers->set('Content-Type', 'application/json; charset=UTF-8');
$response->setStatusCode(200);
return $response;
}
the json show it's fine, but no prefix.
exp:
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
i want that the response will be:
home_categories": [
{
"id": 1,
"h_name": "test",
"h_des": "aaaaa",
"h_des_sell": "",
"h_des_full": "ssssss",
"h_info": "",
"pic": "",
"order": 2
}
]
my current symfony 2 version is 2.6
i try many solutions but the same result
This should work:
$response = new JsonResponse(array('home_categories' => $list));
Related
Hello I want to return a json value in a view from an api,
I am using GuzzleHttp,
but I have the following error
Undefined index: docs (View: /Applications/MAMP/htdocs/sep-api/resources/views/home.blade.php)
THAT'S MY JSON
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "*,score",
"q": "8092316",
"wt": "json"
}
},
"response": {
"numFound": 1,
"start": 0,
"maxScore": 5.1922903,
"docs": [
{
"nombre": "GUADALUPE",
"id": "8092316|C1",
"numCedula": "8092316",
"titulo": "LICENCIATURA EN CONTADURÍA",
"genero": "2",
"institucion": "UNIVERSIDAD VERACRUZANA",
"materno": "LUIS",
"anioRegistro": 2013,
"tipo": "C1",
"paterno": "LUIS",
"timestamp": "2020-09-02T06:20:01.7Z",
"score": 5.1922903
}
]
}
}
THAT'S MY CONTROLLER
public function index($cedulas)
{
$client = new Client([
'base_uri' => 'http://search.sep.gob.mx',
'timeout' => 300,
'Content-Type: application/vnd.api+json',
'Accept: application/vnd.api+json',
]);
$response = $client->request('GET', "http://search.sep.gob.mx/solr/cedulasCore/select?fl=%2A%2Cscore&q={$cedulas}&wt=json");
$posts = json_decode($response->getBody()->getContents(),true);
return view('home', compact('posts'));
THAT'S MY VIEW
#foreach($posts['docs'] as $post)
<h1>name: {{$post['nombre']}}</h1>
#endforeach
as doc is inside response key in json (as u mentioned)
#foreach($posts['response']['docs'] as $post)
<h1>name: {{$post['nombre']}}</h1>
#endforeach
or
$response = $client->request('GET', "http://search.sep.gob.mx/solr/cedulasCore/select?fl=%2A%2Cscore&q={$cedulas}&wt=json");
$responseData = json_decode($response->getBody()->getContents(),true);
$posts = $responseData['response'];
How can I retrieve json data in .json file from API get query of product?
Example: https://api.abcd.com/v1/products/search.json?q=ball
header[key=abc, value=xyz]
From get query fetch json data from postman like
{
"Results": [
{
"Id": 5481192,
"Name": " Shirt",
"Description": " tweens. 100% Cotton.",
"ShortDescription": " Raglan Shirt",
"Number": "4253121",
"ImageUrl": "media/295428",
"VirtualSampleImages": [
{
"Id": 2245428,
"ImageUrl": "virtualsample/2529548"
}
],
"ConfigId": "23",
"Supplier": {
"Id": 613,
"Name": "a",
"AsiNumber": "3529721",
"Phone": {
"Work": "(451) 488-0417",
"$index": 1
}
},
"Price": {
"Quantity": 11,
"Price": 133.7,
"Cost": 61.85,
"DiscountCode": "P",
"CurrencyCode": "USD"
},
"IsNew": false,
"IsConfirmed": false,
"HasVirtualSample": true
}
],
"Selections": {},
"Dimensions": {},
"Links": {
"Self": "?q=shirts&page=1&rpp=1",
"Next": "?q=shirts&page=2&rpp=1"
},
"Query": "shirts",
"Breadcrumb": "\"shirts\"",
"Page": 1,
"ResultsPerPage": 21,
"ResultsTotal": 78,
"SuppliersTotal": 6677,
"CompletedIn": 7
}
I want to save the json data to .json file (automatically) after that to MySQL database with individual columns.
You can simply use curl for the save-to-file process.
curl 'https://api.abcd.com/v1/products/search.json?q=ball' -H 'Accept: application/json, text/plain, */*' -H 'key: abc' -H 'value: xyz' -o dump.json
Then, you can load this file into table with LOAD_FILE :
INSERT INTO table_name (STAMP,file_content) VALUES(NOW(),LOAD_FILE("dump.json"));
The whole process depends on you scripting/programming language. Can you tell us more about your technical context ?
$curl = curl_init();
$options=array(CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",CURLOPT_RETURNTRANSFER =>true,
CURLOPT_ENCODING =>"",CURLOPT_FOLLOWLOCATION =>true,CURLOPT_MAXREDIRS => 10,CURLOPT_TIMEOUT=>30,CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_POSTFIELDS=>"",
CURLOPT_HTTPHEADER=> array("authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
"cache-control: no-cache"), CURLOPT_HEADER=> true);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err)
{
echo "cURL Error #:" . $err;
}
else
{
echo $response;
}
The following image describes my model relationship between User and Room.
There is a Many to Many relationship between them,
and I have resolved the Self Reference issue by JSON.NET
and adding some configurations to the Application_Start function.
It looks like:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};
}
I defined a API like this to return All the users in database as Json.
public ActionResult Index()
{
return Content(JsonConvert.SerializeObject(db.UserSet), "application/json");
}
The point is , when I get a JsonResult , it looks like
(Every "User" has a navigation attribute "Room" )
[
{
"Room": [
{
"User": [
{
"Room": [],
"Id": 3,
"Name": "waterball",
"Account": "pppaass",
"Password": "123"
}
],
"Id": 1,
"Name": "sadafsa"
}
],
"Id": 2,
"Name": "waterball",
"Account": "safasfasd",
"Password": "123"
},
{
"Room": [
{
"User": [
{
"Room": [],
"Id": 2,
"Name": "waterball",
"Account": "safasfasd",
"Password": "123"
}
],
"Id": 1,
"Name": "sadafsa"
}
],
"Id": 3,
"Name": "waterball",
"Account": "pppaass",
"Password": "123"
}, ........
Obviously , the result looks complex ,
How can I get only the Id,Name but NO User attributes of each Room ?
Or what exactly is the common way people handle with this problem?
===========================================================
I have changed my codes to reach my requirement,
but is this actually the common way to resolve this...?
Or does it have some potential problems?
public ActionResult Index()
{
var result = from u in db.UserSet
select new
{
Id = u.Id,
Account = u.Account,
Password = u.Password,
Room = from r in u.Room
select new
{
Id = r.Id,
Name = r.Name
}
};
return Content(JsonConvert.SerializeObject(result), "application/json");
}
I'm working in Symfony2 application and what I'm trying to do is to remove unwanted fields from response and show only fields that I want.
My JSON looks like this:
[
{
"id": 1,
"title": "Granit",
"typeId": {
"id": 1,
"name": "X or Y",
"acroname": "xory",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"pushDate": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460584800
},
"addedAt": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460548644
},
"deviceToShow": {
"id": 2,
"name": "Mobile",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"statusSurvey": false,
"slides": [
{
"id": 1,
"title": "First Question",
"picture1": "160413015724bazinga2.jpg",
"picture2": "160413015724th.jpg",
"idSurvey": 1,
"absolutePathpic1": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724bazinga2.jpg",
"webPathpic1": "uploads/slideSurvey/160413015724bazinga2.jpg",
"absolutePathpic2": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724th.jpg",
"webPathpic2": "uploads/slideSurvey/160413015724th.jpg",
"file": null,
"file1": null
}
],
"categories": []
}
]
I want to remove fields like "initializer": null,"cloner": null, "isInitialized": true and hide timezone object and show only "timestamp".
Here is my controller where I'm doing serializing and creating Json Response.
public function getAction()
{
$em = $this->getDoctrine ()->getManager ();
$survey = $em->getRepository ( 'AppBundle:Survey' )->findAll ();
if ( !$survey ) {
throw $this->createNotFoundException ( 'Data not found.' );
}
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler ( function ( $survey ) {
return $survey->getid ();
} );
$serializer = new Serializer( array ( $normalizer ), array ( $encoder ) );
$jsonContent = $serializer->serialize ( $survey, 'json' );
return new Response( $jsonContent );
}
Thank you.
Try to exclude this fields:
$normalilzer->setIgnoredAttributes(
[
"__initializer__",
"__cloner__",
"__isInitialized__"
]);
Detach entity to remove doctrine2 links to the object
$em->detach($survey);
I'm using a Laravel 5, I just want to know how to use or declare a custom function inside my controller. I have
class UploadController extends Controller
{
function on_request_done($content, $url, $ch, $search) {
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode !== 200) {
print "Fetch error $httpcode for '$url'\n";
return;
}
$responseobject = json_decode($content, true);
if (empty($responseobject['responseData']['results'])) {
print "No results found for '$search'\n";
return;
}
print "********\n";
print "$search:\n";
print "********\n";
$allresponseresults = $responseobject['responseData']['results'];
foreach ($allresponseresults as $responseresult) {
$title = $responseresult['title'];
print "$title\n";
}
}
}
And whenever I call on_request_done inside one of my functions let's say,
public function getParallelApi()
{
define ('SEARCH_URL_PREFIX', 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&filter=0');
$terms_list = array(
"John", "Mary",
"William", "Anna",
"James", "Emma",
"George", "Elizabeth",
"Charles", "Margaret",
"Frank", "Minnie",
"Joseph", "Ida",
"Henry", "Bertha",
"Robert", "Clara",
"Thomas", "Alice",
"Edward", "Annie",
"Harry", "Florence",
"Walter", "Bessie",
"Arthur", "Grace",
"Fred", "Ethel",
"Albert", "Sarah",
"Samuel", "Ella",
"Clarence", "Martha",
"Louis", "Nellie",
"David", "Mabel",
"Joe", "Laura",
"Charlie", "Carrie",
"Richard", "Cora",
"Ernest", "Helen",
"Roy", "Maude",
"Will", "Lillian",
"Andrew", "Gertrude",
"Jesse", "Rose",
"Oscar", "Edna",
"Willie", "Pearl",
"Daniel", "Edith",
"Benjamin", "Jennie",
"Carl", "Hattie",
"Sam", "Mattie",
"Alfred", "Eva",
"Earl", "Julia",
"Peter", "Myrtle",
"Elmer", "Louise",
"Frederick", "Lillie",
"Howard", "Jessie",
"Lewis", "Frances",
"Ralph", "Catherine",
"Herbert", "Lula",
"Paul", "Lena",
"Lee", "Marie",
"Tom", "Ada",
"Herman", "Josephine",
"Martin", "Fanny",
"Jacob", "Lucy",
"Michael", "Dora",
);
if (isset($argv[1])) {
$max_requests = $argv[1];
} else {
$max_requests = 10;
}
$curl_options = array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_USERAGENT, 'Parallel Curl test script',
);
$parallel_curl = new ParallelCurl($max_requests, $curl_options);
foreach ($terms_list as $terms) {
$search = '"'.$terms.' is a"';
$search_url = SEARCH_URL_PREFIX.'&q='.urlencode($terms);
$parallel_curl->startRequest($search_url, 'on_request_done', $search);
}
$parallel_curl->finishAllRequests();
//return "Helloo";
}
I get
call_user_func() expects parameter 1 to be a valid callback, function 'on_request_done' not found or invalid function name
My route
Route::get('/parallelapi', 'UploadController#getParallelApi');
PLEASE NOTE THAT getParallelApi() is under UploadController as well.
The problem is you are passing in the name of the function but it has no idea what class that function exists in. You should be able to do this by passing an array as your callback with the first item being an instance of your controller and the second item being the name of the function.
$parallel_curl->startRequest($search_url, [$this, 'on_request_done'], $search);