loop though json response laravel 5.6 - json

How can i loop though an json response?
I need to loop though eg. $request->device_id.
Then i could save each value returned. (I need to loop though most of the requests).
return response()->json([
'data' => Device::create([
'device_id' => $request->device_id,
'hub_id' => $request->hub_id,
'name' => $request->name,
....
]),
]);
json response looks like:

According to Laravel documentation
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig into JSON arrays:
$name = $request->input('user.name');
however you can use json_decode() function to convert JSON to PHP array. then loop through the array using foreach()

Suppose you have store all the devices into variable name $devices.
$devices = Device::all();
foreach($devices as $device) {
$deviceIds = json_decode($device->devicez_id);
foreach($deviceIds as $deviceId) {
//you will get device id on variable name (deviceId)
}
}

Related

Reading JSON file with different datatypes

I am trying to read a JSON file that contains following data
"{\"studentData\":[{\"Name\":\"Graham\",\"aggregate\":\"86\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"69\",\"sub2\":\"97\",\"sub3\":\"90\"}]},{\"Name\":\"Finley\",\"aggregate\":\"96\",\"regular\":\"false\",\"percentages\":[{\"sub1\":\"95\",\"sub2\":\"91\",\"sub3\":\"73\"}]},{\"Name\":\"Carrillo\",\"aggregate\":\"93\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"90\",\"sub2\":\"84\",\"sub3\":\"80\"}]},{\"Name\":\"Crosby\",\"aggregate\":\"68\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"63\",\"sub2\":\"92\",\"sub3\":\"77\"}]},{\"Name\":\"Small\",\"aggregate\":\"88\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"65\",\"sub2\":\"80\",\"sub3\":\"81\"}]}]}"
I have following code so far
const data = require("./testdata.json");
/*Explore the JSON file and return required JSON data*/
console.log(data)
when I run the code, I see the output in console
But how do I refer to each item in the data
e.g. Name, Regular
When I try to access using below code,
console.log(data.studentData.Name)
I get error
console.log(data.studentData.Name)
^
TypeError: Cannot read property 'Name' of undefined
data.studentData is an array so you need to loop through each value.
With forEach for example:
data.studentData.forEach((individualStudentData) => {
console.log(individualStudentData.Name);
//Do your thing (:
});
Or:
for (let individualStudentData of data.studentData)
a function like .map(() => { ... }
etc. ;)
It looks like data.studentData is actually a JSON Array. So if you wanted to log every name, you'd need to do
const data = require("./testdata.json");
data.studentData.forEach( student => console.log(student.Name));

reverse of toJson() - deserialise JSON to models

I load models with relations (like a book, authors, publisher, keywords) and send it out to the web interface in JSON. Users will edit it there, and then the interface will send it back as JSON. The question is how do I create a model from the JSON (the opposite of toJson() call) and then save it to the database. It would also be helpful if I could compare the original data - reloaded from the db again - with the data I receive from the web layer.
You can decode the JSON once it's received by the server:
$decoded = json_decode( Input::get('json') );
If you want to compare the models one option is grabbing the ID of the model from your decoded JSON (make sure you double check the user has access to it in case they try fudging the data on you), loop over your key/values for your decoded data and match them against each other.
$model = YourModel::find( $decoded->id ); // dont forget to ensure they have access to this model
// Set up an empty array to store anything that's changed
$changes = array();
// Loop over your decoded values
foreach( $decoded as $key => $value ) {
// If the value in your model doesn't match the decoded value, add to the changes array
if( $model->{$key} != $value ) {
$changes[$key] = $value;
}
}
you can convert it to a collection by using collect(json_decode($json)).
collection Docs

how to pass JSON data to view in laravel

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'));

Having trouble with methods for Vimeo's new API to get url of files

I try to get the the data of the field "files" with "quality" with the value "hd". I read about the endpoints and I try to make a request with thee values of this fields.
My problem is I can't obtain the value of the field "files" because is a vector. How is the way to pass this like an endpoint?.
The resource of research is the follow: https://developer.vimeo.com/api/endpoints.
Actually with my code only I can obtein the principal fields but I can't acces to the fileds compound with others.
$client_id = "XXX";
$client_secret= "XXX";
$access_token = "XXX" ;
$lib = new Vimeo($client_id, $client_secret, $access_token);
$response = $lib->request("/videos/videoID")
The return value of the request method will always be an associative array. This associative array will contain three values
body: An associative array containing the full json response
headers: An associative array of response headers
status: The HTTP status code (see http://httpstatus.es for a detailed list)
To access the files array specifically, you would use the following code:
$response['body']['files']
This will contain an array of file objects for you to loop through.
foreach ($response['body']['files'] as $file) {
// use a $file
}
NOTE: Only PRO members have access to video files, and even then only to their own files.

zf2 How to save json return value to a variable

i have this code to return json
return new JsonModel(array(
'id' => $id,
'name' => 'ana',
));
that code will return this
{"id":"83493","name":"ana"}
my question is how do i save id value to a variable. lets just say my variable is $a. How do i save 83493 to $a?
I assume you are returning the json array from a controller's action to a view file.
Was this action called via some ajax call? If yes then, on success of that ajax call, you will have something as -
$.ajax({
.....
.....
.....
success: function(data) {
var a = data.id; //Here variable a will have value as 83493
},
});
As you are sending the array and not just a single value, the data parameter in the success function will act like a object and so id and name will become its properties.
Properties should be accessed via dot (.) operator Eg: data.id and data.name
I hope this is what you are expecting, please let us know if its not.