Converting string to object with Javascript
17,576
"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
}
Related videos on Youtube
Author by
Admin
Updated on May 27, 2022Comments
-
Admin almost 2 years
I am trying to convert to object this string.
"JwtBody { user_id: 1, auth_id: 1}"
-
jwebb over 6 yearsPossible duplicate of String to object in JS
-
unional over 6 yearsWrite a parser to strip out
JwtBody
and then use JSON.parse(). -
charlietfl over 6 years@JaromandaX invalid as json due to no quotes
-
Jaromanda X over 6 yearsahhh, yes, damn :p
-
-
kamoroso94 over 6 yearsThis will fail because the string is not well-formed JSON.
-
Admin over 6 yearsI can not use jQuery, in the backend I have a string as I said above and I need to convert it to an object.
-
Admin over 6 yearsThis will fail because the string not in this format
-
Jaromanda X over 6 yearsor just
eval("JwtBody { user_id: 1, auth_id: 1}".replace(/([^}]+?)({.*})/, '$1=$2'));
- results in a var named JwtBody with the value of the object -
Alexis Wilke over 5 yearsThe
1
don't need to be quoted. Actually, they probably should not. -
Alexis Wilke over 5 yearsOnly
eval()
is not safe... If the string includes code, it's going to be executed.