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
}
Share:
17,576

Related videos on Youtube

Admin
Author by

Admin

Updated on May 27, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to convert to object this string.

       "JwtBody { user_id: 1, auth_id: 1}"
    
    • jwebb
      jwebb over 6 years
      Possible duplicate of String to object in JS
    • unional
      unional over 6 years
      Write a parser to strip out JwtBody and then use JSON.parse().
    • charlietfl
      charlietfl over 6 years
      @JaromandaX invalid as json due to no quotes
    • Jaromanda X
      Jaromanda X over 6 years
      ahhh, yes, damn :p
  • kamoroso94
    kamoroso94 over 6 years
    This will fail because the string is not well-formed JSON.
  • Admin
    Admin over 6 years
    I 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
    Admin over 6 years
    This will fail because the string not in this format
  • Jaromanda X
    Jaromanda X over 6 years
    or 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
    Alexis Wilke over 5 years
    The 1 don't need to be quoted. Actually, they probably should not.
  • Alexis Wilke
    Alexis Wilke over 5 years
    Only eval() is not safe... If the string includes code, it's going to be executed.