JSON response in Laravel 5.5 adds additional fields - php

I am trying to return JSON in a controller using this line:
return response()->json( $return );
$return contains two key/value pairs.
When I try to validate the response in a test, it fails because the response does contain additional fields:
Unable to find JSON:
[{
"statusCode": 665,
"msg": "auth missing"
}]
within response JSON:
[{
"headers": [],
"original": {
"statusCode": "665",
"msg": "auth missing"
},
"exception": null
}].
I have no idea how the additional keys get there and why the source array is nested in the source key.
How can I make sure that only the array that I pass to response()->json is returned?

Answering my own question here:
The problem was that $return was already a json encoded object. So this weird formatting is the result of converting json into json.

Related

search through JSON Object for specific key

I'm getting a JSON response from an API provider which I can't change, and there are lots of nested objects in the response and then there is an object which I need, below is just the example of response actual response has a lot of nested objects and then the match object,
I can easily access the match object but in some case, the API provider add some more object above it as shown in the 2nd response where he added the group and then there is match object which I need,
still by using some if, else we can get through it.
but are there any methods or ways available that can directly give me access to the match object or can find the match object?
I'm using laravel 5.8
and tried some of the collection methods none of them work on objects.
in actual response, I have to go 7 steps nested.
//1nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"match" : {
score_a:0,
score_b:1
}
}
}]
//2nd API response
[{
"version": "2.258.2",
"sport": "badminton",
"lang": "en",
"generated_utc": "2021-07-28T13:58:16+00:00",
"method": {
"method_id": "258",
"name": "get_matches"
"group":{
"match" : {
score_a:0,
score_b:1
}
}
}
}]
Thank You!

how to accessing data in a php object

I am trying to the balance in a PHP object, I tried everything but am getting array to string conversion error, here is the string
{
"status": true,
"message": "Balances retrieved",
"data": [
{
"currency": "NGN",
"balance": 0
}
]
}
its a response from a remote server, i am trying to get the balance, i tried
$response->data->balance
json_decode($response)->data->balance
json_decode($response[0])->data->balance
but none of them worked, the response from the remote server is stored in a variable called $response
How can i get the balance from the response
Data is an array
json_decode($response)->data[0]->balance
Take a look at this example, that I created: http://sandbox.onlinephpfunctions.com/code/414f23b1a09221ed5bd7f299f5eb73a2f9f932b1
First you decode the JSON string
Then access data array at the index 0, so data[0]
And then data[0]->balance, access object property 'balance'
Gerard's answer is right.
Also you can naviguate the result of a json_decode function in array mode.
<?php
$json = '{
"status": true,
"message": "Balances retrieved",
"data": [
{
"currency": "NGN",
"balance": 0
}
]
}';
$response = json_decode($json);
echo $response["data"][0]["balance"];
echo $response->data[0]->balance;
Using a variable to register the decode answer will save you time.

Filter JSON Result against RQL Query String with PHP

I've an Symfony 4 Api Project which has to filter their Result by an RQL String.
Request:
localhost/api?q=altProductId=in=(456)
The altProductId is not part of database. It is added by the controller.
The Output is a JSONResponse like:
Response:
{
"data": [
{"altProductId": 123},
{"altProductId": 456},
{"altProductId": 789}
]
}
And it should be for the above request:
{
"data": [
{"altProductId": 456}
]
}
I've already tried to parse the Query with Graviton\RqlParser, but do not know how to filter the Json Result with this or another way.
Can someone help?

Can't access object variables in PHP from Facebook Graph API

I have a request to the Facebook Graph API that returns a post from a facebook account.
I am simply trying to access the data instance of the object returned in PHP but everything I have tried returns NULL.
Sample response
{
"data": [
{
"id": " 111111111111111111100000",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}
I want to get at the array of objects data provides so I can MVC the data returned in a larger response.
This doesn't currently work:
$response->data; // returns null
$response[0]->data; // returns null
$response->data[0]; // returns null
Feel I'm missing something obvious.
first decode it with json_decode then trying to access the data object
$res = json_decode($response);
print_r($res->data);
print_r($res->data[0]->id);
print_r($res->data[0]->message);
code
you have to use first json decode function so you can get the data from the json response.
$response = '{
"data": [
{
"id": "143384725674462_1592535354092718",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}';
$response = json_decode($response);
print_r($response->data[0]->id);
print_r($response->data[0]->message);

JMSSerializerBundle and Symfony 2 - Output Doctrine/ODM to JSON file

I am trying to retrieve all records and display them in a JSON file.
My current function retrieves all Events that belong to a specific user.
/**
* create json files from doctrine/mongo
* #Route("/createjson", name="createjson")
*/
public function createJson()
{
// check user authentication
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$dm = $this->get('doctrine_mongodb')->getManager();
$repository = $dm->getRepository('AppBundle:Event');
$events = $repository->findBy(array('user' => $this->getUser()));
$serializer = SerializerBuilder::create()->build();
$result = $serializer->deserialize($events, 'AppBundle\Document\Event', 'json');
var_dump($result);
exit;
}
This is not working because some of the elements passed into the serializer are of an array format. Error I am getting.
Warning: json_decode() expects parameter 1 to be string, array given
500 Internal Server Error - ContextErrorException
However if I use the inbuilt Symfony Serializer it works fine:
$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($events, 'json');
return new Response($reports);
However the JSON to be produced will be different to my Document/Entity hence why I want/need to use the JMSSerializerBundle.
For example, a record looks like this:
[{
"id": "572041b3288b560e5e00451c",
"name": "Test",
"date": "2016-04-27T05:25:00+1000",
"enddate": "2016-04-30T11:55:00+1000",
"location": {
"name": "Sydney, NSW"
},
"key": {
"id": "1g43g34g34g23f32g32G32gGSDF"
},
"user": {
"id": "57203174288b560e5e0044da"
}, ...
}]
But I only want to display (output) to JSON
[{
"id": "572041b3288b560e5e00451c",
"name": "Test",
"date": "2016-04-27T05:25:00+1000",
"location": "Sydney, NSW"
}]
How would I go about doing this? There is not much documentation on JMSSerializerBundle online.
Edit: I should mention that the database collection I am querying has a relation to the User collection which is managed by FOSUserBundle. I'm not sure if this has any relation to my problem however
You should look at the documentation of the bundle, may be you will find more information
http://jmsyst.com/bundles/JMSSerializerBundle
http://jmsyst.com/libs/serializer/master/usage
You seems to use the wrong function of the serializer. In your case, you seems to need to get a json from your user object, so you need to use
$serializer = SerializerBuilder::create()->build();
$result = $serializer->serialize($events, 'AppBundle\Document\Event', 'json');
serialize($object):string : get a string from an object
deserialize($string):object : get an object from a representation of an object (json, xml...).

Categories