Skip to content

Instantly share code, notes, and snippets.

@openqubit
Last active January 8, 2017 19:20
Show Gist options
  • Save openqubit/5f66f4d5fce39acd81f7809a6f85ae43 to your computer and use it in GitHub Desktop.
Save openqubit/5f66f4d5fce39acd81f7809a6f85ae43 to your computer and use it in GitHub Desktop.
Stringfy object functions in javascript https://jsfiddle.net/p24b9f8n/38/
var stringify = function(obj, prop) {
var placeholder = '____PLACEHOLDER____';
var fns = [];
var json = JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
fns.push(value);
return placeholder;
}
return value;
}, 2);
json = json.replace(new RegExp('"' + placeholder + '"', 'g'), function(_) {
return fns.shift();
});
return 'var ' + prop + ' = ' + json + ';';
};
var rides = {
brand: {
type: "String",
label: "搜尋",
max: "100"
},
model: {
type: "String",
label: "Tìm kiếm",
max: "100"
},
fueltype: {
type: "String",
label: "Пошук",
allowedValues: ['Petrol', 'Diesel', 'Hybrid', 'Electric'],
},
bodystyle: {
type: "String",
label: "بحث",
allowedValues: ['Convertibles', 'Coupes', 'Hatchbacks', 'Vans', 'Sedans', 'Suvs', 'Trucks', 'Wagons'],
optional: "true"
},
topspeed: {
type: "Number",
label: "חיפוש",
optional: "true"
},
power: {
type: "Number",
label: "Power (HP)",
optional: "true"
}
};
var processed = stringify(rides,'rides');
var find = '"type": "String"';
var find_number = '"type": "Number"';
var find_boolean_true = '"optional": "true"';
var find_boolean_false = '"optional": "false"';
var find_max = '"max": "100"';
var re = new RegExp(find, 'g');
var re_number = new RegExp(find_number, 'g');
var re_boolean_true = new RegExp(find_boolean_true, 'g');
var re_boolean_false = new RegExp(find_boolean_false, 'g');
var re_max = new RegExp(find_max, 'g');
var processed = processed.replace(re, '"type": String');
var processed = processed.replace(re_number, '"type": Number');
var processed = processed.replace(re_boolean_true, '"optional": true');
var processed = processed.replace(re_boolean_false, '"optional": false');
var processed = processed.replace(re_max, '"max": 100');
console.log(processed);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment