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?
-
Why are you using this format?Blender– Blender2013年06月01日 07:50:05 +00:00Commented Jun 1, 2013 at 7:50
-
Where are you getting these strings from?Blender– Blender2013年06月01日 07:54:57 +00:00Commented Jun 1, 2013 at 7:54
-
user puts them into shellKosmetika– Kosmetika2013年06月01日 07:56:38 +00:00Commented Jun 1, 2013 at 7:56
3 Answers 3
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);
3 Comments
"{ name: John, family: Resig }" you need to split it before on ,{ name: John, email: { $exists: true }}If you can get '{"name":"John"}' then you can just decode it as JSON.
Comments
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
5 Comments
{ data: $exists }, seems only spliting & slicing may help