<h1>Detect format type from string</h1>
<p>
Open console, try adding some tests.
</p>
<p>
This the script used on Zapier to prepare data to be send to Algolia -> <a href="https://zapier.com/developer/invite/72601/a7ad1ab340d8d677673330901662d3cb/">Zapier + Algolia Zap Beta</a>
</p>
JavaScript
var Zap = {
update_pre_write: function(bundle) {
var myRecord = {};
var data = bundle.action_fields_full.record;
var supported = ['object','number','boolean','string'];
function tryType(o,f){
switch(f) {
case 'boolean':
var b = o.toLowerCase();
if (b !== 'true' && b !== 'false'){
throw "not a boolean";
}
return JSON.parse(b);
case 'object':
var s;
if (o.match(/[^\d]\,/g)){
s = o.split(/\,(?! )/);
}
if (o.startsWith("{") || o.startsWith("[")){
return JSON.parse(o.replace(/([a-zA-Z0-9]+?):([\"\'\s]+)/g, '"$1":$2').replace(/'/g,'"'));
} else if (s.length > 1) {
return s;
} else {
throw "not an object";
}
break;
case 'number':
var n = o.replace(/(\d)\,(\d)/g,'$1$2');
if (isNaN(n)){
throw "not a number";
}
return (n*1);
case 'string':
if(typeof o === undefined || o === null) break;
return o;
}
}
Object.keys(data).forEach(function(key,index) {
function upgradeFormat() {
for (var i = 0; i < supported.length; i++) {
try {
return tryType(data[key],supported[i]);
}
catch(error) {
//console.log(error);
}
}
}
var keys = key.split('.');
if (keys.length > 1){
if (myRecord[keys[0]] === undefined) myRecord[keys[0]] = {};
myRecord[keys[0]][keys[1]] = upgradeFormat();
} else {
myRecord[key] = upgradeFormat();
}
});
myRecord = JSON.stringify(myRecord);
return {
url: bundle.request.url,
method: bundle.request.method,
auth: bundle.request.auth,
headers: bundle.request.headers,
params: bundle.request.params,
data: myRecord
};
}
};
//tests
var tests = [
{
string:...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.