Emilios1995
Emilios1995

Reputation: 507

How to Create JS Object from string

I have a string whose value is (according to console.log()):

j:{"address":"North Road 34 ","zip":"00002 ","state":"Texas ","city":"Dallas ","country":"US"}

I dont know why it starts with that letter 'j', but i am only interested in what is inside it. I have tried JSON.parse() but throws an error: 'unexpected token: 'j'.

The eval() solution doesn't seems to work either , it throws 'unexpected token: ':'

Thank You!

Upvotes: 0

Views: 408

Answers (4)

jkyadav
jkyadav

Reputation: 1282

You can use this trick.

var v="j:{"address":"North Road 34 ","zip":"00002 ","state":"Texas ","city":"Dallas  ","country":"US"}"

var rpVal=v.replace("j:","");

var yourObject=new someObject();

yourObject= eval("(" + rpVal+ ")");

This way you will achieve your goal easily.

Upvotes: 0

RobG
RobG

Reputation: 147453

Like plalx's answer but leading junk isn't hard coded:

var s = 'j:{"address":"North Road 34 ","zip":"00002 ","state":"Texas ","city":"Dallas  ","country":"US"} ';

// Strip everything up to leading "{":
var obj = JSON.parse(s.substring(s.indexOf('{')));

Upvotes: 1

plalx
plalx

Reputation: 43728

Well... the only explanation is that it shouldn't start with j: since it's invalid JSON, but it does (probably because of a bug).

You can easily fix your string to make it valid by removing the invalid prefix from the JSON string.

var obj = JSON.parse(yourString.replace(/^j:/, ''));

Upvotes: 3

iplus26
iplus26

Reputation: 2647

Just remove the don't-know-where-come-from j: and then JSON.parse() will work. Show more code if you need help.

Upvotes: 0

Related Questions