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
Related
Currently, I'm using the JSON Casting defined in my Model
protected $casts = ['input_params'=>'json'];
When retrieving data I'm able to get the input_param attribute as a JSON.
But when I'm inserting or updating a row the attribute is being saved as string.
I still need to use JSON decode to make sure that it will be saved as JSON.
Does the Laravel model have an equivalent for this code that can be defined on the Model?
$data['input_params'] = json_decode($data['input_params'], true);
In this situation, I recommend you to :
Type your input_params database field as JSON. You can use Laravel migration for that :
$table->json('input_params');
Cast your property input_params as array like that :
protected $casts = ['input_params' => 'array'];
If you do this, Laravel will automatically save your array into JSON format and cast your JSON stored data to array when you will retrieve them. It is a convenient way to manipulate your data without manage json encode and decode. You can find more info here (Laravel 9)
Step : Define accessor for that attributes.
Example:
protected $casts = ['input_params'];
public function setInputParamsAttribute($input_params)
{
return json_decode($input_params);
}
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)
}
}
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.
I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John
I'm working with moose objects in perl. I want to be able to covert the moose objects I make directly to JSON.
However, when I use use MooseX::Storage to covert the objects, it includes a hidden attribute that I don't know how to remove the "__CLASS__" .
Is there a way to remove this using MooseX::Storage ? (For now I am just using MooseX::Storage to covert it and using JSON to remove the "__ CLASS __ " attribute by going to a hash . ) The solution I am doing for now is a problem, because I have to do it everytime I get the JSON for every object(so when I write the JSON output to a file, to be loaded I have to make the changes everytime, and any referanced objects also have to be handled)
package Example::Component;
use Moose;
use MooseX::Storage;
with Storage('format' => 'JSON');
has 'description' => (is => 'rw', isa => 'Str');
1;
no Moose;
no MooseX::Storage;
use JSON;
my $componentObject = Example::Component->new;
$componentObject->description('Testing item with type');
my $jsonString = $componentObject->freeze();
print $jsonString."\n\n";
my $json_obj = new JSON;
my $perl_hash = $json_obj->decode ($jsonString);
delete ${$perl_hash}{'__CLASS__'};
$jsonString = $json_obj->encode($perl_hash);
print $jsonString."\n\n";
MooseX::Storage is not particularly suited to this task. It's designed to enable persistent storage of Moose objects (that's why it adds the __CLASS__ field) so they can be retrieved by your program later.
If your goal is to construct objects for a JSON API, then it would probably be much easier to just pass your object's hashref directly to JSON.pm.
use JSON -convert_blessed_universally;
my $json_obj = JSON->new->allow_blessed->convert_blessed;
my $jsonString = $json_obj->encode( $componentObject );
The -convert_blessed_universally option (in addition to being a mouthful) will cause JSON.pm to treat blessed references (objects) as ordinary Perl structures which can be translated to JSON directly.
EDIT: Looks like you have to add the allow_blessed and convert_blessed options to the JSON object also.