3

I am trying to convert to object this string.

   "JwtBody { user_id: 1, auth_id: 1}"
4
  • 1
    Possible duplicate of String to object in JS Commented Nov 21, 2017 at 1:20
  • 1
    Write a parser to strip out JwtBody and then use JSON.parse(). Commented Nov 21, 2017 at 1:28
  • 1
    @JaromandaX invalid as json due to no quotes Commented Nov 21, 2017 at 1:54
  • ahhh, yes, damn :p Commented Nov 21, 2017 at 2:19

6 Answers 6

10

"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
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
Only eval() is not safe... If the string includes code, it's going to be executed.
0

Could you use JSON.parse()?

I haven't used it myself, but it looks like create a variable and use JSON.parse("string") to have it converted into an object.

So, for your example it would be something like:

var object = JSON.parse("JwtBody { user_id: 1, auth_id: 1}");

1 Comment

This will fail because the string is not well-formed JSON.
0

Not exactly sure what you're trying to do.

You could try something like this:

var str = '{"user_id": "1", "auth_id": "1"}';
var obj = $.parseJSON(str);

Be sure to have jquery like this:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

2 Comments

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.
The 1 don't need to be quoted. Actually, they probably should not.
0

If you can't change data from example:

var parsedData = {};
var str = "JwtBody { user_id: 1, auth_id: 1}";

function getRawJSON(str){
    return str.split(' ').map((el, index)=>{return index>0 ? el : ''}).join('');
}

function formatingValidJSON(str){
    // From https://stackoverflow.com/questions/9637517/parsing-relaxed-json-without-eval
    return str
    .replace(/:\s*"([^"]*)"/g, function(match, p1) {
        return ': "' + p1.replace(/:/g, '@colon@') + '"';
    })
    .replace(/:\s*'([^']*)'/g, function(match, p1) {
        return ': "' + p1.replace(/:/g, '@colon@') + '"';
    })
    .replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
    .replace(/@colon@/g, ':')
}

str = formatingValidJSON(getRawJSON(str));
try{
    parsedData = JSON.parse(str);
    console.log('Your parsed data:', parsedData);
}
catch(e){
    console.log('Your data is wrong');
}

Comments

0

This JSON-like string can be parsed using vanilla JavaScript and regex by:

  1. Reducing string to only characters that String.match() JSON-like object string
  2. String.replace() property names to enclose matched names with quotations
  3. parsing object with JSON.parse

var jwtBodyString = "JwtBody { user_id: 1, auth_id: 1}";

`//1 match on only JSON within string
jwtBody = jwtBodyString.match(/{[^}]+}/).toString();`    

//2 enclose property names to prevent errors with JSON.parse()
jwtBody = jwtBody.replace(/([a-zA-Z]+):/g,'"$1":'));

//3 obtain object
var myJwtBodyObject = JSON.parse(jwtBody);

Comments

-1

Use JSON.parse()

Also, you're javascript string is invalid JSON which means it's invalid javascript. It should look like this:

JSON.parse('{"jwtbody" : { "user_id" : 1, "auth_id" : 1}}');

This will give you the corresponding javascript object you want.

1 Comment

This will fail because the string not in this format