0

Is it possible to create an object from a string content?

For example, I have a string "{ name: John }" how can I simply parse it to create an object { name: 'John' } ?

UPDATE

Unfortunately JSON.parse won't work for me, there can be also some tricky strings (if you used mongodb you know), e.g. { name: John, email: { $exists: true } }

Maybe there is another solution like mongodb query parser?

asked Jun 1, 2013 at 7:28
3
  • Why are you using this format? Commented Jun 1, 2013 at 7:50
  • Where are you getting these strings from? Commented Jun 1, 2013 at 7:54
  • user puts them into shell Commented Jun 1, 2013 at 7:56

3 Answers 3

2

this is one way to do it. //code for trim method

 if(typeof String.prototype.trim !== 'function') {
 String.prototype.trim = function() {
 return this.replace(/^\s+|\s+$/g, ''); 
 }
 }
 var s = "{ name: John }";
 var arr = s.substring(1,s.length-1).trim().split(':');
 var obj = {};
 obj[arr[0]]=arr[1];
 alert(obj.name);
answered Jun 1, 2013 at 7:35
Sign up to request clarification or add additional context in comments.

3 Comments

What about "{ name: John, family: Resig }" ?
this kind of technique I already use, for "{ name: John, family: Resig }" you need to split it before on ,
but in my case there can be even more complicated techniques like { name: John, email: { $exists: true }}
0

If you can get '{"name":"John"}' then you can just decode it as JSON.

answered Jun 1, 2013 at 7:29

Comments

0

Working jsFiddle Demo

Your string must be valid JSON format:

var s = '{ "name": "John", "family": "Resig" }';

Then you can parse it with JSON.parse:

var o = JSON.parse(s);

And you can use the object o:

alert(o.name); // John
alert(o.family); // Resig
answered Jun 1, 2013 at 7:40

5 Comments

unfortunately I can't be sure that it will be correct JSON, a string could be like this { data: $exists }, seems only spliting & slicing may help
@Kosmetika How are you generating your JSON? All server side languages has ability to generate valid JSON string.
it's not a JSON, it's simple string that user puts into shell
@Kosmetika I don't think it's a correct way to do this. Imagine user wants something like this: { "fullname": "Resig, John: jQuery Creator" } (an object with one pair). How this must be input? { fullname: Resig, John: jQuery Creator } (an object with two pairs)?
yeah, sounds not ok.. in ideal it can be typed like { fullname: "Resig, John: jQuery Creator" }..

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.