I'm trying to return array from laravel controller. Here is my code,
$find = array("id"=>1,"id"=>2,"id"=>3);
$result = array("data"=>$find);
return $result;
My result is :
{
"data":
[
{"id":1},
{"id":2},
{"id":3}
]
}
The result is in JSON format.
But i want to get it in Array Format like :
{
"data":
[
["id":1],
["id":2],
["id":3]
]
}
It's impossible as ["id":1] is not a valid JSON.
You can always validate JSON here
Related
I have 2 api responses and want to compare only one of the column values 'logline'. How can I do it?
I have tried the following, but the Test Result is always Failed.
pm.test("status Check", function () {
var jsonData = pm.response.json();
var resp_arr = jsonData.results[0].series[0].values;
_.each(jsonData, (arrItem) => {
pm.expect(arrItem.status).to.be.oneOf(resp_arr);
})
});
Basically, I want to compare 2 JSON responses which are in array format and only the second column.
My API Response: Both response are in same format & structure
{
"results":[
{
"statement_id":0,
"series":[
{
"name":"process_log",
"columns":[
"time",
"logline"
],
"values":[
[
"2020-09-21T12:41:01.199552139Z",
"9/10/2020 15:57:31.073\t abc"
],
[
"2020-09-21T12:41:01.199824076Z",
"9/10/2020 15:57:31.078\t xyz"
]
]
}
]
}
]
}
So I am trying to return an array of objects with my Laravel collection using the following code:
/**
* View a user's chat rooms.
*
* return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory\
*/
public function viewChatRooms()
{
$user = Auth::user(); // #var User $user
$username = $user->username;
$rooms = Room::with('messages')->get()
->filter(function ($val) use ($username){
foreach ($val->users as $user) {
if($user === $username){
return $val;
}
}
});
return response(['rooms' => $rooms]);
}
Instead of returning an array of objects, the response returns the following:
{
"rooms": {
"0": {...},
"3": {...}
}
}
This is the desired result:
{
"rooms": [
{...},
{...}
]
}
Kind of stumped by this, could some one guide me in the right direction?
You Can use array_value function of PHP when returning response like this:
return response()->json([
'rooms' => array_values($rooms->toArray())
]);
Laravel Collection Methods for Getting only values of Collection
https://laravel.com/docs/5.8/collections#method-values
So
return response()->json([
'rooms' => $rooms->values()->toArray()
]);
The issue was that I didn't rebase the array since it skipped a few keys. I fixed it by simply using array_values() like so:
$rooms = Room::with('messages')->get()
->filter(function ($val) use ($username){
foreach ($val->users as $user) {
if($user === $username){
return $val;
}
}
});
return response(['rooms' => array_values($rooms->toArray())]);
I think that you will find that doing this within your DB query will be better performance wise.
Something like this:
$rooms = Room::whereHas('users', function(user) use ($username) {
return $user == $username
})
->with('messages')
->get();
To return an array of objects, you can use the all method.
Instead of returning a collection of objects, it returns an array of objects.
For example, User::all(); returns an Eloquent collection which is structured like so:
[
{App\User},
{App\User},
{App\User}
]
Whereas, the other answers suggest using ->toArray() which returns an array of arrays, not an array of objects, e.g.:
[
[
'id' => 123,
'name' => 'example'
...
],
[
...
]
]
I'm passing the following request to laravel api, but when I dump the input request, Laravel is returning an empty array.
{
"expense_type" : "payment",
"description" : "test",
"notes" : "My notes",
"expense_date": "2019-01-15",
"cost" : 100.50,
"group_id" : 1,
"shares" : [
{
"user_id" : 1,
"paid_share" : 100.50,
"owed_share" : 00.00
},
{
"user_id" : 2,
"paid_share" : 00.00,
"owed_share" : 50.25
},
{
"user_id" : 3,
"paid_share" : 00.00,
"owed_share" : 50.25
}
]
}
The output when dumping the input $request->all() is []
can some one help if there is something wrong in the request
When you send data in request as json data then $request->all() will always return empty. In order to access data in $request->all() variable you have to send form data not json data.
So, when json data is sent through api, you can access it as array in the controller like this:
$data = json_decode(file_get_contents("php://input"), true);
Now, you can access the values like $data['expense_type']
I hope you understand.
I am using curl to get some data, then parsing it with JsonSlurper.
The data structure is
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
So if I'm not mistaken, the entire thing is considered an object. But there is an array in the object (results) which contains objects in that array.
I need to get the length of the results array. When I try to do json.result.length, I receive a null.
How can I get the length of the results array?
def list = ['curl', '-u', 'user:pass', "http://localhost:8081/..."].execute()
def json = new JsonSlurper().parseText(list.text)
println json.result.size()
What I see is, you are using incorrect property to get the size. Need to use results instead of result. Thats is the reason you are seeing that error as result is null(because there is no such property)
Here is working script and gets output as 3:
import net.sf.json.groovy.JsonSlurper
def jsonText='''{
"results" : [
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-27"
},
{
"uri" : "http://localhost:8081/artifactory/api/storage/...",
"created" : "2015-11-30"
}
]
}'''
def json = new JsonSlurper().parseText(jsonText)
println json.results.size()
assert 3 == json.results.size(), "Array size is not matching"
It will be:
def response = ... // your response as text, stream..
def parsed = new JsonSluper().parse(response) // parseText if string
println parsed.results.size()
BTW: size() is for Collection, length for String, note method vs field. In groovy you can use size() for String as well.
{
"projects":
[
{
"platform": "java",
"name":"abc"
},
{
"platform": ".net",
"name":"abcd"
}]
}
for this json file list.json how to get json size or number of applications count.
below code worked for me in groovy as i was using in it my jenkinsfile.
import groovy.json.JsonBuilder
import groovy.json.JsonOutput
import groovy.io.FileType
def applicationCount()
{
jsonFile1 = 'list.json'
def json1 = readJSON file: jsonFile1
totalApplication = json1.projects.size()
println "count" + totalApplication
println "applicationname" + json1['projects'][0]['name']
}
I have a json response coming in from a php file, the json response looks as below results:
[
{
"header": "Client ID",
"dataindex": "clientID"
},
{
"header": "Client Name",
"dataindex": "clientName"
},
{
"header": "Progress Bar",
"dataindex": "progressBar"
}
]
Now I want to copy this data into an array in the following way
var allColumns = [];
//loop through the json response
var singleColumn = [];
singleColumn['header'] = Client ID from the json response whose key is header
singleColumn[dataindex'] = clientID from the json response whose key is header.
Please note: I need to do this is extjs3.
If I am getting you correctly you are getting the JSON as a string from an ajax call to your PHP handler in a string format and you want to cast it into a Javascript array of coloumn objects.
you can do it like this:
var allColumns = Ext.decode(YOUR PHP JSON FORMATTED RESULT);
this will allow you to iterate over the result set as an in memory javascript array of objects like this:
for(var i=0 ; i < allColumns.length; i++){
allColumns[i].header ...
allColumns[i].dataindex ...
}
I hope I got you right...