How to exclude an object's id property before or during $.toJSON - javascript

I'm writing a custom REST adapter for ember-data users with a django rest framework app and need to build a JSON string to do POST/PUT. The only problem is I can't seem to chain another jQuery method after the $.toJSON that removes this.
So far I have an ember.js object that I plan to extract each property from, except my django app doesn't want the id to go along with the HTTP POST
I can get a legit string like so
$.param(record.toJSON());
This results in the following
id=0&username=dat
I'd like a quick way to exclude id when I do this toJSON (does this exist w/ out writing it by hand?) Using jQuery 1.8+
Thank you in advance

Turns out this was really simple
var json_data = record.toJSON();
delete json_data.id;
var data = $.param(json_data);
Now instead of
id=0&username=dat
I now get
username=dat

Related

SAP Cloud SDK for Javascript: Filter on Expanded Entities

I know I am reopening an old one (Perform filter on expanded entity with SAP Cloud SDK), but it was a while ago and was referencing the Java version of the API used to consume an S/4 HANA service.
I'm testing the Javascript version of the API against the SuccessFactors OData API, which is indeed able to perform filters on expanded entities, like so:
<API_HOST>/odata/v2/PerPerson?$filter=personalInfoNav/firstName eq 'MARCO'&$expand=personalInfoNav&$select=personalInfoNav/firstName, personalInfoNav/lastName&$top=20
Translated into the SDK, it would be (TypeScript):
const personList: Array<PerPerson> =
await PerPerson.requestBuilder().getAll().top(20)
.select(
PerPerson.DATE_OF_BIRTH,
PerPerson.PERSONAL_INFO_NAV.select(
PerPersonal.PERSON_ID_EXTERNAL,
PerPersonal.FIRST_NAME,
PerPersonal.LAST_NAME,
PerPersonal.GENDER
)
).filter(PerPersonal.FIRST_NAME.equals('MARCO'))
.execute({ destinationName: this.configService.get<string>('ACTIVE_DESTINATION') });
But this code does not compile because of the incompatibility of types for the filter function, which here expects a "PerPerson" type and not "PerPersonal".
I was not able to find anything about this.
Considering that the plain OData query works perfectly, anyone has been able to make this work?
Update:
I didn't initially understand that Successfactors offered this functionality on top of the protocol. There are two possible workarounds I can think of:
use new Filter, e.g.:
PerPerson.requestBuilder().getAll().top(20)
.select(
...
).filter(
new Filter('personalInfoNav/firstName', 'eq', 'MARCO')
)
...
If this doesn't work, you can call build on the request builder instead of execute, which gives you the ODataRequest object from which you can get the URL, which you'd then have to manipulate manually. Then you should be able to use the executeHttpRequest function to execute this custom request object against a destination.
Let me know if one of these work for you!
Original answer:
filtering on expanded entities on OData v2 is only possible if the relationship between the two entities is 1:1. In the case the code would look like this:
PerPerson.requestBuilder().getAll().top(20)
.select(
PerPerson.DATE_OF_BIRTH,
PerPerson.PERSONAL_INFO_NAV.select(
PerPersonal.PERSON_ID_EXTERNAL,
PerPersonal.FIRST_NAME,
PerPersonal.LAST_NAME,
PerPersonal.GENDER
)
).filter(
PerPerson.PERSONAL_INFO_NAV.filter(
PerPersonal.FIRST_NAME.equals('MARCO')
))
...
If, however, the relationship is 1:n, filtering is not possible.
Hope that helps!

How can I create a Get request in Node.js to get specific object from json?

I am optimizing an api, therefore I need to use only data that is relevant for my analysis. I have created a route that pull out of the objects, but I just need 4 of them (account_manager, fronter, closer, management_fee and sales_date)
I am currently doing this:
you can use .find() with projection to retrieve only the relevant field
try this :
const model_CancellationKPI = await CancellationKPI.find({},{
account_manager:1,
fronter:1,
closer:1,
management_fee:1,
sales_date:1
}).sort({sales_date:-1})

Laravel - Modifying data for API only for convenience

Let's assume the following data that is exactly being returned like it's stored into database:
[
{
"user_name": "User 1",
"photo_file": "user1.jpg"
},
{
"user_name": "User 2",
"photo_file": "user2.jpg"
}
// ...
]
I want to use this data in a JavaScript application but I'd like to append a full path of the user's photo, like doing a treatment for the data before returning it to the API. How can I do that using Laravel?
I assume at present you're just converting the results of your query into JSON and returning that. This works, but it does mean the response is tightly coupled to your database structure, which is a bad idea. Ideally you should have a layer of abstraction to handle adding and formatting data, kind of like a view layer in MVC.
There are plenty of solutions for this. I use Fractal for my Laravel API's. It allows you to easily customise the output of a particular endpoint by specifying a transformer that will render that object for you. That way you can easily choose the data to display and format it how you wish.
Accessors are good for this.
Let's assume your data is stored in a model called Customer. I would write an accessor like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $appends = ['photo_file']; // In order to see the new attribute in json dumps
public function getPhotoPathAttribute()
{
$name = $this->getAttribute('photo_file');
if(!isset($name))
return null;
return '/full/path/to/image/' . $name;
}
}
This way you can now call $customer->photo_path and it will return `/full/path/to/image/image_name.jpg' (or null if the attribute is not set).
Edit:
In order to show this attribute in jsons (without specifically calling $model->photo_path) you will also need to add protected $appends = ['photo_file'] to the model (updated).
I would recommend against overriding original name (so I leave photo_file attribute untouched).
If you are building Laravel API, sure, as Matthew said, go and check Fractal. But don't forget to Dingo, the best tool for building API at Laravel. And it uses Fractal too.

Converting PHP object to JSON object using only Javascript

I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!

Databinding to Windows 8 ListView

I'm having massive problems with databinding to a ListView in a Windows 8 app using Javascript.
Inside the "activated" event on default.js I have written some code to get some data from a web service and push it into an array. This bit works OK and the array is populated.
The problem I have is that the app won't recognise the data. I have this code in a page called inspections.html:
data-win-options="{itemTemplate: select('#imageTextListCollectionTemplate'),
itemDataSource: dataList.dataSource,
layout: {type: WinJS.UI.ListLayout}}
and then in the "activated" event I declare:
var dataList = new Array();
and push the data from the web service into this array. But at runtime I get an error that says something along the lines of "can't find dataSource on undefined dataList".
I've done some of the examples on the MS website and in one of them it creates a dummy dataset and references it from a namespace. I kinda think that what I'm missing here is a namespace too but I don't know what the namespace for default.js is. Or maybe I'm wrong and it's something totally different.
Please help - this is so fundamental (and should be easy) but I can't get my head around it.
Do you want to create datalist in HTML or javascript?
It seems you want to create it from JavaScript. Assuming that you have already pushed your data into array from your webservice, you only need to call:
var dataList = new WinJS.Binding.List(array);
now accessing dataList.dataSource is perfectly valid.
Also, to create the datalist you don't always need an array. You could probably start with an empty list and then keep inserting data directly into the data list from web services, like:
var dataList = new WinJS.Binding.List([]);
dataList.push(value1);
dataList.push(value2);
...
Hope it helps. Let me know if you have any more questions.
If you are getting troubled by assigning datasource in HTML side
Prefer js side like
var list = new WinJS.Binding.List(array here);
listView.itemDataSource = list.dataSource;
by using this you can easily go through the data which you are binding to ListView.

Categories

Resources