How to convert a string in a function into an object?
The trick is to use parse
. For instance:
> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
[1] 1 2 3 4 5 6 7 8 9 10
See also this Q/A: Evaluate expression given as a string
How to convert a string into an object with javascript and return some keys in snake_case?
You can use map
and reduce
:
function myOrder(str) {
return str.length === 0 ?
{} :
str.split(',')
.map(s => s.match(/(?<qty>\d+)\s*(?<name>.+)/).groups)
.reduce((res, {name, qty}) => ({
...res, [name.replace(/\s/g, '_')]: +qty
}), {});
}
console.log( myOrder('') );
console.log( myOrder('2 coca cola, 4 beer') );
console.log( myOrder(' 46 foos & bars, 0fizz') );
Converting string to object with Javascript
"JwtBody { user_id: 1, auth_id: 1}" is obviously not a standard json string,So you can try this.
function strToObj(str){
var obj = {};
if(str&&typeof str ==='string'){
var objStr = str.match(/\{(.)+\}/g);
eval("obj ="+objStr);
}
return obj
}
Convert string object to object
So I tried to help
if (inlineScriptsTexts.includes('zvkDL '+'=')) {
const str = inlineScriptsTexts.trim()
.replace('zvkDL '+'=',"")
.replace(/'/g,'"')
.replace(/\/\/.*?\n/g,"")
.replace(/\};/g,"}")
console.log(str)
console.log(JSON.parse(str));
}
But the function is a BIG problem
// the reason it won't work:// this is as good as a representation of the object as can be made
const obj = { "language": "cs", "currency": "czk", "event": "akurva", "ecommerce": { "purchase": { "actionField": { "id": 555, "revenue": 535535, "shipping": 3535, } } }, "eventCallback": function() { setGTMcookie(555); }, // this will NOT be seen by JSON
"eventTimeout": 2000, "eventCookie": { "name": "dasd", "expires": "asdsadd", "value": "funguje to", } } console.log(JSON.stringify(obj))
/*
window.onload = function() { let objExist = false; let inlineScripts = document.body; let inlineScriptsBlocks = Array.from(inlineScripts.getElementsByTagName('script')); inlineScriptsBlocks.forEach(scriptBlock => { let inlineScriptsTexts = scriptBlock.innerText; if (inlineScriptsTexts.includes('zvkDL '+'=')) { const str = inlineScriptsTexts.trim().replace('zvkDL '+'=',"").replace(/'/g,'"').replace(/\/\/.*?\n/g,"").replace(/\};/g,"}") console.log(str) console.log(JSON.parse(str)); } });}*/
<script> zvkDL = { 'language': 'cs', 'currency': 'czk', 'event': 'akurva', 'ecommerce': { 'purchase': { 'actionField': { 'id': 555, 'revenue': 535535, 'shipping': 3535, } } }, 'eventCallback': function() { setGTMcookie(555); // Jak se bude callback jmenovat nechám na vás. Jen to musí být srozumitelné. Pozor na scope JS callbacku. }, 'eventTimeout': 2000, 'eventCookie': { 'name': 'dasd', 'expires': 'asdsadd', 'value': 'funguje to', } };</script>
Convert function parameter in string into parameter in object
You could convert the string to an object that the function accepts.
function toObj(str) {
const a = str.split(/,.?/g);
return a.reduce((p, c) => {
const kv = c.replace(/'/g, '').split(':');
p[kv[0]] = kv[1];
return p;
}, {});
}
toObj(str); // { location: "L1", row_name: "r1", value: "18.4" }
DEMO
Given a string describing a Javascript function, convert it to a Javascript function
There's also the Function object.
var adder = new Function("a", "b", "return a + b");
Related Topics
How to Have Conditional Formatting of Data Frames in R Shiny
R-Shiny Using Reactive Renderui Value
Range Join Data.Frames - Specific Date Column with Date Ranges/Intervals in R
How to Adjust Facet Size Manually
Stylecolorbar Center and Shift Left/Right Dependent on Sign
Histogram with "Negative" Logarithmic Scale in R
Why Is Stat = "Identity" Necessary in Geom_Bar in Ggplot
How to Correctly Interpret Ggplot's Stat_Density2D
Is There a Reason to Prefer Extractor Functions to Accessing Attributes with $
R Table Function: How to Sum Instead of Counting
Merge/Combine Columns with Same Name But Incomplete Data