user7453724
user7453724

Reputation:

Converting string to object with Javascript

I am trying to convert to object this string.

   "JwtBody { user_id: 1, auth_id: 1}"

Upvotes: 3

Views: 26540

Answers (6)

sl2782087
sl2782087

Reputation: 136

"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
}

Upvotes: 10

Matthew Thurston
Matthew Thurston

Reputation: 760

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);

Upvotes: 0

Cami Rodriguez
Cami Rodriguez

Reputation: 1087

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');
}

Upvotes: 0

Mark
Mark

Reputation: 10998

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.

Upvotes: -1

Howard
Howard

Reputation: 3758

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>

Upvotes: 0

Lisa Cee
Lisa Cee

Reputation: 27

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}");

Upvotes: 0

Related Questions